<template>
  <div>
    <a-select
      v-model="text"
      style="width: 100%"
      show-search
      allow-clear
      dropdown-class-name="select-i18n-dropdown"
      :filter-option="false"
      :default-active-first-option="false"
      :placeholder="$t('PLACESELECT')"
      @change="handleChange"
      @search="remoteMethod"
    >
      <div slot="dropdownRender" slot-scope="menu">
        <v-nodes :vnodes="menu" />
        <a-divider style="margin: 4px 0" />
        <div
          class="select-add"
          @mousedown="(e) => e.preventDefault()"
          @click="handleAddI18n"
        >
          <a-icon type="plus" style="margin: 3px 5px 0 0" /> {{ $t("ADD") }}
        </div>
      </div>
      <a-select-option
        v-for="item in i18nList"
        :key="item.i18nCode"
        :value="item.i18nCode"
      >
        {{ item.i18nCode }}({{ item.dataValue }})
      </a-select-option>
    </a-select>
    <MegaModal
      :title="$t('I18N_INFO')"
      :visible="visible"
      :centered="true"
      :mask-closable="false"
      :destroy-on-close="true"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <MegaForm
        ref="MegaForm"
        :query-param="form"
        :query-param-item="formItem"
      ></MegaForm>
    </MegaModal>
  </div>
</template>

<script>
import { Modal as MegaModal, Form as MegaForm } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaModal,
    MegaForm,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  props: {
    // 需要展示的key
    value: String,
    clientTypeList: {
      type: Array,
      default: () => [],
    },
    i18nTypeList: {
      type: Array,
      default: () => [],
    },
    rules: Boolean,
  },
  data() {
    return {
      text: undefined,
      menu: [],
      i18nList: [],

      visible: false,
      form: {
        id: null,
        clientType: undefined,
        i18nCode: undefined,
        type: undefined,
      },
    };
  },
  computed: {
    languages() {
      return this.$store.state.app.languages || [];
    },
    formItem() {
      const languageFormItem = this.languages.reduce(
        (obj, item) => ({
          ...obj,
          [item.value]: {
            label: item.label,
            type: "textarea",
            rules: ["required"],
          },
        }),
        {}
      );
      return this.$observable("formItem", {
        clientType: {
          label: () => this.$t("MOM_VERSION"),
          itemType: "select",
          options: [].concat(this.clientTypeList),
          optionsProps: {
            label: "label",
            value: "value",
          },
          rules: ["required"],
        },
        i18nCode: {
          label: () => this.$t("CODE"), // 编码
          rules: ["required"],
        },
        type: {
          label: () => this.$t("TYPE"),
          itemType: "select",
          options: [].concat(this.i18nTypeList),
          optionsProps: {
            label: "label",
            value: "value",
          },
          rules: ["required"],
        },
        ...languageFormItem,
      });
    },
  },
  mounted() {
    if (
      [this.clientTypeList.length, this.i18nTypeList.length].every(
        (item) => item === 0
      )
    ) {
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:CORE:MOM_VERSION`,
        method: "get",
      }).then((res) => {
        this.formItem.clientType.options = res.data.data || [];
      });
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:CORE:I18N_TYPE`,
        method: "get",
      }).then((res) => {
        this.formItem.type.options = res.data.data || [];
      });
    }
    if (this.value) {
      this.remoteMethod(this.value);
      this.text = this.value;
    }
  },
  methods: {
    remoteMethod(val) {
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/i18n/list-for-select`,
        method: "get",
        params: { searchKey: val, isCancelApiLoad: true },
      }).then((res) => {
        this.i18nList = res.data.data.filter((item, index) => index < 100);
      });
    },
    handleAddI18n() {
      this.languages.forEach((item) => {
        this.$set(this.form, item.value, undefined);
      });
      this.form.clientType = this.formItem.clientType.options[0]?.value;
      this.form.i18nCode = undefined;
      this.form.type = undefined;
      this.visible = true;
    },
    handleChange(value) {
      this.text = value;
      this.$emit("input", this.text);
      this.$emit("change", this.text);
    },
    handleCancel() {
      this.visible = false;
    },
    handleOk() {
      this.$refs.MegaForm?.$refs.MegaRuleForm.validate((valid) => {
        if (valid) {
          const { clientType, i18nCode, type } = this.form;
          const req = {
            clientType,
            i18nCode,
            type,
            items: this.languages.map((item) => ({
              dataValue: this.form[item.value],
              i18nCode,
              languageCode: item.value,
              languageName: item.label,
            })),
          };
          this.$axios({
            url: `${ApiConstant.PREFIX_CORE}/api/sys/i18n`,
            data: req,
            method: "post",
          }).then(() => {
            this.$message.success(this.$t("ADD_SUCCESS"));
            this.visible = false;
            this.handleChange(this.form.i18nCode);
            this.remoteMethod(this.text);
          });
        }
      });
    },
  },
};
</script>

<style lang="less">
.select-i18n-dropdown {
  .select-add {
    height: 32px;
    padding: 4px 8px;
    color: #005583;
    text-align: center;
    cursor: pointer;
  }
}
</style>
