<template>
  <div id="containt">
    <el-tabs v-model="activeName" class="tab-box">
      <el-tab-pane :label="$t1('列表')" name="second">
        <div class="tree-box fl">
          <div class="tit"><b>{{ $t1('数据类型') }}</b></div>
          <el-tree
            :props="defaultProps"
            :load="loadNode"
            node-key="id"
            ref="tree"
            highlight-current
            lazy
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            class="tree-list"
            icon-class="el-icon-arrow-down"
            v-if="showTree"
          ></el-tree>
        </div>
        <label id="labBtn">
          <div class="icon">
            <i class="el-icon-more"></i>
            <i class="el-icon-more"></i>
          </div>
        </label>
        <div class="main-right fr" style="padding-left:6px;">
          <div class="grid-height">
            <vxe-grid ref="table-m1" v-bind="vxeOption" @resizable-change="$vxeTableUtil.onColumnWitchChange"
                      @custom="$vxeTableUtil.customHandle">
              <template #form>
                <tableForm :formData.sync="formData" @searchEvent="searchEvent" @resetEvent="resetEvent">
                  <template #buttonLeft>
                    <vxe-button status="primary" class="button-sty" icon="el-icon-plus"
                                @click="openFieldTranslationEditDialog()" :disabled="!currentDataType.id" v-if="isDev">
                      {{ $t1('新增') }}
                    </vxe-button>
                    <base-table-export :option="{ title: $t1('多语言'), targetRef: 'table-m1'}"
                                       :parent-target="_self" :disabled="!currentDataType.id" v-if="isDev"/>
                    <vxe-button status="primary" class="button-sty" icon="el-icon-download" @click="importExcel"
                                :disabled="!currentDataType.id" v-if="isDev">{{ $t1('导入') }}
                    </vxe-button>
                    <vxe-button status="success" class="button-sty" icon="el-icon-download" @click="jsonImport">
                      {{ $t1('导入发布') }}
                    </vxe-button>
                    <vxe-button status="success" class="button-sty" icon="el-icon-upload2" @click="jsonExport"
                                v-if="isDev">{{ $t1('导出发布') }}
                    </vxe-button>
                    <!--                    <langTagAddButton :option="addProjectTagOption" v-if="isDev"></langTagAddButton>
                                        <langTagDeleteButton :option="deleteProjectTagOption" v-if="isDev"></langTagDeleteButton>-->
                  </template>
                  <template #buttonRight>
                    <vxe-button icon="el-icon-brush" class="button-sty" @click="resetEvent" type="text" status="primary"
                                plain>{{ $t1('重置') }}
                    </vxe-button>
                    <vxe-button status="warning" icon="el-icon-search" class="button-sty" @click="searchEvent">
                      {{ $t1('搜索') }}
                    </vxe-button>
                  </template>
                  <template #dataTypeName>
                    <vxe-form-item :title="$t1('数据类型')+':'" field="dataTypeName">
                      <template v-slot>
                        <el-input v-model="currentDataType.dataTypeName" size="small" disabled/>
                      </template>
                    </vxe-form-item>
                  </template>
                  <!--                  <template #tag>
                                      <vxe-form-item :title="$t1('多语言标签')+':'" field="tag">
                                        <template v-slot>
                                          <el-input
                                            class="search-input"
                                            max="200"
                                            :value="getTabNames()"
                                            @clear="
                                              checkTags = [];
                                            "
                                            v-el-readonly
                                            clearable
                                          >
                                            <i slot="suffix" class="el-input__icon el-icon-search" @click="openLangTagDialog3"></i>
                                          </el-input>
                                        </template>
                                      </vxe-form-item>
                                    </template>-->
                </tableForm>
              </template>
              <!--              <template #tag="{row}">
                              <langTagView v-model="row.fieldTranslationTagDTOs" :readonly="true"></langTagView>
                            </template>-->
            </vxe-grid>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <fieldTranslationEditDialog v-if="showFieldTranslationEditDialog" :visiable.sync="showFieldTranslationEditDialog"
                                :_dataId.sync="dataId" :currentDataType="currentDataType"
                                @confirm="confirmFieldTranslationEditDialog"></fieldTranslationEditDialog>
<!--    <langTagDialog v-if="showLangTagDialog3"
                   :visiable.sync="showLangTagDialog3"
                   @confirm="confirmLangTagDialog3"
                   :rows="checkTags"
                   :multi="true"></langTagDialog>-->
  </div>
</template>

<script>
import fieldTranslationEditDialog from "../../../views/user/fieldTranslation/editDialog.vue";
import {treeScollx} from '@base/utils/global.js';
import {getBdFlag} from "@base/api/user";
import tableForm from "@base/components/table/tableForm.vue";
/*import langTagDialog from "../../../views/user/lang_tag/dialog.vue";
import langTagAddButton from "@base/components/langTag/addButton.vue";
import langTagDeleteButton from "@base/components/langTag/deleteButton.vue";
import langTagView from "@base/components/langTag/view.vue";*/

export default {
  name: 'fieldTranslation:list',
  components: {
    tableForm, fieldTranslationEditDialog/*, langTagView,
    langTagDialog, langTagAddButton, langTagDeleteButton*/
  },
  data() {
    return {
      activeName: 'second',
      dataId: 0,
      showEdit: false,
      vxeOption: {},
      formData: {},

      defaultProps: {
        label: 'dataTypeName', //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: 'leaf'
      },
      currentDataType: {},
      dataTypeGroup: "fieldTranslation",
      fieldTranslationDicts: [],
      fieldTranslationDictMap: {},
      showTree: false,
      showFieldTranslationEditDialog: false,
      languageSettings: [],
      addProjectTagOption: {
        url: USER_PREFIX + `/fieldTranslation/saveTag`,
        tableDatas: () => {
          return this.$refs["table-m1"].getCheckboxRecords(true);
        },
        reqData: (tagDatas, tableDatas) => {
          let sids = tableDatas.map(item => item.sid);
          let tagCodes = tagDatas.map(item => item.tagCode);
          let reqData = {
            tagCodes,
            sids
          };
          return reqData;
        },
        callback: () => {
          this.searchEvent()
        }
      },
      deleteProjectTagOption: {
        url: USER_PREFIX + `/fieldTranslation/deleteTag`,
        tableDatas: () => {
          return this.$refs["table-m1"].getCheckboxRecords(true);
        },
        reqData: (tagDatas, tableDatas) => {
          let sids = tableDatas.map(item => item.sid);
          let tagCodes = tagDatas.map(item => item.tagCode);
          let reqData = {
            tagCodes,
            sids
          };
          return reqData;
        },
        callback: () => {
          this.searchEvent()
        }
      },
      showLangTagDialog3: false,
      checkTags: [],
      isDev: true,

    };
  },
  async mounted() {
    treeScollx({target: this, type: 'default'});
    /*await this.$getBaseDicts({
      code: "fieldTranslation",
      success: ({dicts, dictMap}) => {
        this.fieldTranslationDicts = dicts;
        this.fieldTranslationDictMap = dictMap;
      }
    });*/
    await this.initLanguageSetting();
    // this.getBdEnv();
    this.initTableList();
  },
  methods: {
    initLanguageSetting() {
      return this.$http({
        url: USER_PREFIX + `/language_setting/listPage`,
        method: `post`,
        data: {
          enabled: true
        },
        isLoading: true,
        modalStrictly: true,
        success: res => {
          this.languageSettings = res?.objx?.records || [];
        }
      });
    },
    searchEvent() {
      this.$refs['table-m1'].commitProxy('reload');
    },
    resetEvent() {
      this.formData = {};
      this.$refs['table-m1'].commitProxy('reload');
    },
    openEditDialog(id) {
      this.dataId = !id || typeof id == 'object' ? 0 : id;
      this.activeName = 'first';
      this.$openEditView('showEdit');
    },
    getSearchParam() {
      let tagCodes = null;
      if (this.checkTags.length) {
        tagCodes = this.checkTags.map(item => item.tagCode);
      }
      return {
        ...this.formData,
        dataTypeCode: this.currentDataType.dataTypeCode,
        tagCodes
      };
    },
    initTableList() {
      let that = this;
      let dataTypeMap = {
        "business": this.$t1('全局对照表'),
        "menus": this.$t1('菜单对照表'),
      }
      let syncColumns = []
      this.languageSettings.forEach(item => {
        syncColumns.push({
          title: item.languageName,
          field: item.translationField,
          width: 150
        })
      })
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'user_fieldTranslation_list-m1',
        path: USER_PREFIX + '/fieldTranslation/listPage',
        param: () => {
          return this.getSearchParam();
        },
        config: {
          proxyConfig: {
            autoLoad: false
          }
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('字段编码'),
            field: 'fieldCode',
            width: 150,
            fixed: 'left'
          },
          {
            title: this.$t1('中文'),
            field: 'translation1',
            width: 150,
            fixed: 'left'
          },
          ...syncColumns,
          {
            title: this.$t1('数据类型'),
            field: 'dataTypeName',
            width: 150,
            slots: {
              default: ({row}) => {
                return dataTypeMap[row.dataTypeCode] || '';
              }
            }
          },
          /*{
            title: this.$t1('多语言标签'), field: 'tag', width: 250, slots: {default: "tag"}, params: {
              exportVal: ({row}) => {
                if (row.fieldTranslationTagDTOs) {
                  return row.fieldTranslationTagDTOs.map(item => item.tagName).join(",")
                }
              }
            }
          },*/
          {
            field: 'modifyDate',
            title: this.$t1('更新时间'),
            width: 150
          },
          {
            width: 47,
            fixed: 'right',
            title: '',
            sortable: false,
            slots: {
              default: ({row}) => {
                return [
                  <div>
                    <a
                      href="javascript:void(0);"
                      class="a-link"
                      onclick={() => {
                        this.openFieldTranslationEditDialog(row.id);
                      }}
                    >
                      <el-tooltip enterable={false} effect="dark" content={this.$t1('查看')} placement="top"
                                  popper-class="tooltip-skin">
                        <i class="el-icon-edit"/>
                      </el-tooltip>
                    </a>
                  </div>
                ];
              }
            }
          }
        ],
        searchColumns: [
          {
            title: this.$t1('数据类型'),
            field: "dataTypeName",
            type: "input",
            common: true,
            disabled: true,
            defaultValueEnabled: false,
            slot: "dataTypeName"
          },
          {title: this.$t1('字段编码'), field: "fieldCode", type: "input", common: true},
          {title: this.$t1('中文'), field: "translation1", type: "input", common: true},
          // {title: this.$t1('多语言标签'), field: "tag", type: "input", common: true, slot: "tag"},
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
        this.showTree = true;
      });
    },
    handleNodeClick(data, node, v) {
      this.currentDataType = data;
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {

      let rows = [
        {
          dataTypeName: this.$t1('全局对照表'),
          dataTypeCode: 'business',
          id: 'business',
          leaf: true,
        },
        {
          dataTypeName: this.$t1('菜单对照表'),
          dataTypeCode: 'menus',
          id: 'menus',
          leaf: true,
        }
      ]
      resolve(rows);
      if (rows.length) {
        this.$nextTick(() => {
          let data = node.childNodes[0].data;
          this.$refs.tree.setCurrentKey(data);
          this.currentDataType = data;
          this.searchEvent();
        })
      }
    },

    openFieldTranslationEditDialog(id) {
      this.dataId = !id || typeof id == 'object' ? 0 : id;
      if (!this.dataId) {
        if (!this.currentDataType) {
          this.$baseAlert(this.$t1('请选择数据类型'));
          return
        }
      }
      this.showFieldTranslationEditDialog = true;
    },
    confirmFieldTranslationEditDialog(row) {
      this.searchEvent();
    },
    importExcel() {
      let that = this;
      let currentDataType = this.currentDataType;
      that.$excelImport({
        title: this.$t1('多语言导入（{dataTypeName}）', {dataTypeName: currentDataType.dataTypeName}),
        prefix: USER_PREFIX,
        excel: USER_PREFIX + '/excelTemplate/fieldTranslation/fieldTranslation.xlsx',
        multi: false,
        saveUrl: USER_PREFIX + '/fieldTranslation/importData',
        defaultValue: {dataTypeCode: currentDataType.dataTypeCode},
        callback: () => {
          that.searchEvent();
        }
      });
    },
    jsonImport() {
      this.$langImport({
        saveUrl: USER_PREFIX + '/fieldTranslation/import2Publish',
        lang: true,
        callback: () => {
          this.searchEvent();
        }
      });
    },
    jsonExport() {
      this.$baseConfirm(this.$t1('您确定要导出发布吗？'))
        .then(() => {
          this.$http({
            url: USER_PREFIX + "/fieldTranslation/export2Publish",
            method: `post`,
            data: this.getSearchParam(),
            isLoading: true,
            success: res => {
              let content = res.objx
              if (content && content !== "[]") {
                this.downloadTxt(content)
              } else {
                this.$baseAlert(this.$t1('不存在需要导出的数据'))
              }
            }
          });
        })
        .catch(() => {
        });
    },
    downloadTxt(content) {
      // 创建Blob对象
      const blob = new Blob([content], {type: 'text/plain;charset=utf-8'});
      // 创建URL
      const url = URL.createObjectURL(blob);
      // 创建a标签
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'fieldTranslation.txt');
      document.body.appendChild(link);
      // 触发下载
      link.click();
      // 清理
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },
    openLangTagDialog3() {
      this.showLangTagDialog3 = true;
    },
    confirmLangTagDialog3(rows) {
      this.checkTags = rows;
    },
    getTabNames() {
      return this.checkTags.map(item => item.tagName).join(",");
    },
    getBdEnv() {
      getBdFlag({
        success: res => {
          this.isDev = res.objx == 1
        }
      });
    }
  }
};
</script>
