<template>
  <div class="allUserPoerationModal" ref="allUserPoerationModal"></div>
  <a-modal
    class="allUserPoeration_modal generalModel"
    v-model:visible="operationsModal"
    :footer="null"
    :get-container="() => $refs.allUserPoerationModal"
    width="50%"
    height="55rem"
    :maskClosable="false"
    :centered="true"
    :closable="false"
    :mask="true"
    wrapClassName="#app"
    :keyboard="false"
  >
    <div class="generalModel_btn">
      <div class="generalModel_closeIcon" @click.stop="cancelDsign()">
        <svg
          width="100%" height="100%"
          viewBox="0 0 46 46"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <circle cx="23" cy="23" r="23" fill="black" fill-opacity="0.3" />
          <rect
            x="32.5063"
            y="12"
            width="3"
            height="29"
            rx="1.5"
            transform="rotate(45 32.5063 12)"
            fill="white"
          />
          <rect
            x="34.6274"
            y="32.5059"
            width="3"
            height="29"
            rx="1.5"
            transform="rotate(135 34.6274 32.5059)"
            fill="white"
          />
        </svg>
      </div>
    </div>
    <div class="modal_title_text">
      <div>{{ title.label }} {{ $t('admin.User') }}</div>
    </div>
    <div class="allUserPoeration_center admin_page">
      <div class="admin_state_item">
        <span>{{ $t('admin.UserName') }}: <span>*</span></span>
        <input
          v-model="userName"
          :placeholder="$t('admin.enterUserName')"
          type="text"
          style="width: 250px"
        />
      </div>
      <div class="admin_state_item">
        <span>{{ $t('admin.UserEmail') }}: <span>*</span></span>
        <input
          v-model="userEmail"
          :placeholder="$t('admin.enterEmail')"
          type="text"
          style="width: 250px"
        />
      </div>
      <div class="admin_state_item">
        <span>{{ $t('admin.Password') }}: <span>*</span></span>
        <input
          @focus="focus"
          @blur="blur"
          v-model="password"
          :placeholder="$t('admin.enterPassword')"
          type="password"
          style="width: 250px"
        />
      </div>
      <div class="admin_state_item">
        <span>{{ $t('admin.MaximumCredits') }}:</span>
        <input
          v-model="credits"
          :placeholder="$t('admin.enterCredits')"
          type="text"
          style="width: 250px"
        />
      </div>
      <div class="admin_state_item" v-if="title?.value == 'Edit'">
        <span>{{ $t('admin.SubscribePlan') }}: <span>*</span></span>
        <a-select
          v-model:value="subscriptionPlanId"
          style="width: 250px"
          :options="activePlanOptions"
          :field-names="{ label: 'name', value: 'id' }"
          :placeholder="$t('admin.SelectPlan')"
        ></a-select>
      </div>
    </div>
    <div class="allUserPoeration_btn admin_page">
      <div class="admin_search_item" @click="cancelDsign">{{ $t('admin.Close') }}</div>
      <div class="admin_search_item" @click="setOk">{{ $t('admin.OK') }}</div>
    </div>
  </a-modal>
  <div class="mark_loading" v-show="loadingShow">
    <a-spin size="large" />
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  watch,
  onMounted,
  nextTick,
  toRefs,
  computed,
} from "vue";
import { Https } from "@/tool/https";
import { Modal, message } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { formatTime, isEmail } from "@/tool/util";
import md5 from "md5";
import { useI18n } from 'vue-i18n'
export default defineComponent({
  components: {},
  props: {
    planOptions: {
      type: Array,
      default: () => []
    }
  },
  emits: ["searchHistoryList"],
  setup(props, { emit }) {
	const {t} = useI18n()
    const { planOptions } = toRefs(props)
    // 筛选出状态为 ACTIVE 的订阅计划
    const activePlanOptions = computed(() => {
      if (!planOptions.value || !Array.isArray(planOptions.value)) {
        return []
      }
      return planOptions.value.filter((plan: any) => plan.status === 'ACTIVE')
    })
    let operations = reactive({
      operationsModal: false,
      operationsEdit: false,
      loadingShow: false,
      title: null,
    });
    let operationsData = reactive({
      accountId: -1,
      userName: "",
      userEmail: "",
      password: "",
      oldPassword: "",
      credits: "",
      subscriptionPlanId: "",
      oldSubscriptionPlanId: ""
    });
    let state = ref([
      {
        label: "visitor",
        value: "0",
      },
      {
        label: "yearly",
        value: "1",
      },
      {
        label: "monthly",
        value: "2",
      },
      {
        label: "trial",
        value: "3",
      },
    ]);
    let init = (funStr, data) => {
      operations.operationsModal = true;
      operations.operationsEdit = true;
      operations.title = funStr;
      if (funStr.value == "Add") operations.operationsEdit = false;
      if (funStr.value == "Edit") {
        operationsData.accountId = data.id;
        operationsData.userName = data.userName;
        operationsData.userEmail = data.userEmail;
        operationsData.password = data.userPassword?data.userPassword:null;
        operationsData.oldPassword = data.userPassword;
        // operationsData.validStartTime='2024-08-05T00:00:06'
        // operationsData.validEndTime='2024-08-05T00:00:06'
        operationsData.credits = data.creditsUsageLimit;
        operationsData.subscriptionPlanId = data.subscriptionPlanId || "";
        operationsData.oldSubscriptionPlanId = data.subscriptionPlanId || "";
        // operationsData.accountId = data.accountId
        // operationsData.userName = data.userName
        // operationsData.userEmail = data.userEmail
        // operationsData.validStartTime = formatTime(data.validStartTime)
        // operationsData.validEndTime = formatTime(data.validEndTime)
      }
      if (funStr.value == "Add") {
        operationsData.subscriptionPlanId = "";
        operationsData.oldSubscriptionPlanId = "";
      }
    };
    let focus = (event) => {
      if (operationsData.password == operationsData.oldPassword) {
        operationsData.password = "";
      }
    };
    let blur = (event) => {
      console.log(operationsData.password == "" && operationsData.oldPassword);
      if (operationsData.password == "" && operationsData.oldPassword) {
        operationsData.password = operationsData.oldPassword;
      }
    };
    let setAddData = () => {
      return {
        creditsUsageLimit: operationsData.credits,
        userEmail: operationsData.userEmail,
        userPassword: operationsData.password?md5(operationsData.password + "abc"):'',
        userName: operationsData.userName,
        subscriptionPlanId: operationsData.subscriptionPlanId
      };
    };
    let setEditData = () => {
      return {
        id: operationsData.accountId,
        creditsUsageLimit: operationsData.credits,
        userName: operationsData.userName,
        userEmail: operationsData.userEmail,
        userPassword:
          operationsData.password == operationsData.oldPassword
            ? null
            : md5(operationsData.password + "abc"),
        subscriptionPlanId: operationsData.subscriptionPlanId
      };
    };
    let cancelDsign = () => {
      operationsData.accountId = -1;
      operationsData.userName = "";
      operationsData.userEmail = "";
      operationsData.password = "";
      operationsData.credits = "";
      operationsData.subscriptionPlanId = "";
      operationsData.oldSubscriptionPlanId = "";
      operations.operationsModal = false;
    };
    let setOk = () => {
      let data;
      if (operations.title?.value == "Add") {
        data = setAddData();
        if (!isEmail(data.userEmail)) {
          message.info(t('admin.jsContent1'));
          return;
        }
        if (
          !data.userName ||
          !data.userEmail ||
          !data.userPassword
        )
          return message.warning(t('admin.jsContent2'));
        Https.axiosPost(Https.httpUrls.addOrUpdateSubAccount, data).then(
          (rv) => {
            if (rv) {
              cancelDsign();
              emit("searchHistoryList");
            }
          }
        );
      } else {
        data = setEditData();
        if (!isEmail(data.userEmail)) {
          message.info("The email format is incorrect");
          return;
        }
        if (!data.userName || !data.userEmail || !data.subscriptionPlanId)
          return message.warning("Please check the input box marked with *");
        const needSwitchPlan =
          operationsData.subscriptionPlanId &&
          operationsData.subscriptionPlanId !==
            operationsData.oldSubscriptionPlanId;
        Https.axiosPost(Https.httpUrls.addOrUpdateSubAccount, data).then(
          (rv) => {
            if (rv) {
              if (needSwitchPlan) {
                Https.axiosGet(
                  Https.httpUrls.switchSubAccountSubscribePlan,
                  {
                    params: {
                      targetSubscriptionPlanId: operationsData.subscriptionPlanId,
                      subAccId: operationsData.accountId,
                    },
                  }
                );
              }
              cancelDsign();
              emit("searchHistoryList");
            }
          }
        );
      }
    };
    return {
      ...toRefs(operations),
      ...toRefs(operationsData),
      state,
      cancelDsign,
      init,
      focus,
      blur,
      setOk,
      planOptions,
      activePlanOptions
    };
  },
  data() {
    return {};
  },
  mounted() {},
  methods: {},
});
</script>
<style lang="less" scoped>
:deep(.allUserPoeration_modal) {
  .ant-modal-body {
    display: flex;
    flex-direction: column;
  }
}
</style>
<style lang="less" scoped>
.allUserPoeration_modal {
  .closeIcon {
    z-index: 2;
  }
  .allUserPoeration_btn {
    display: flex;
    flex-direction: row;
    height: auto;
    justify-content: flex-end;
    padding: 1rem 0;
    .admin_search_item {
      margin-bottom: 0;
    }
  }
  .allUserPoeration_center {
    flex: 1;
    overflow-y: auto;
    flex-direction: row;
    flex-wrap: wrap;
  }
}
</style>
