<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue/lib';
import { onMounted, reactive } from 'vue';
import useAppStore from '@/store/modules/app';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { changeValue } from '@/api/system/config';
const appStore = useAppStore();
const { t } = useI18n();

type StateType = {
  edite: boolean;
  loading: boolean;
  copyright: string;
  flag: string;
};

let state: StateType = reactive({
  edite: false,
  loading: false,
  copyright: '',
  flag: '',
});

/**进入可编辑 */
function fnEdit(v: boolean) {
  state.edite = v;
  if (!v) {
    state.copyright = appStore.copyright;
    state.flag = appStore.copyright;
  }
}

/**提交保存 */
function fnSave() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: `确认要提交当前变更的版权声明吗?`,
    onOk() {
      // 发送请求
      const hide = message.loading(t('common.loading'), 0);
      state.loading = true;
      changeValue({ key: 'sys.copyright', value: state.copyright }).then(
        res => {
          state.loading = false;
          hide();
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success('提交保存成功', 3);
            appStore.copyright = state.copyright;
            fnEdit(false);
          } else {
            message.error(res.msg, 3);
          }
        }
      );
    },
  });
}

onMounted(() => {
  state.copyright = appStore.copyright;
  state.flag = appStore.copyright;
});
</script>

<template>
  <a-row :gutter="16">
    <a-col :lg="12" :md="12" :xs="24" style="margin-bottom: 30px">
      <a-form layout="vertical" v-if="state.edite">
        <a-form-item>
          <a-input
            v-model:value="state.copyright"
            allow-clear
            :maxlength="40"
            placeholder="输入版权声明"
          ></a-input>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            :disabled="state.copyright === state.flag"
            @click="fnSave"
          >
            提交保存
          </a-button>
          <a-button style="margin-left: 10px" @click="fnEdit(false)">
            {{ t('common.cancel') }}
          </a-button>
        </a-form-item>
      </a-form>

      <template v-else>
        <div class="sys-copyright">{{ state.copyright }}</div>
        <a-button type="dashed" @click="fnEdit(true)"> 编辑 </a-button>
      </template>
    </a-col>
    <a-col :lg="12" :md="12" :xs="24">
      <a-typography>
        <a-typography-paragraph>
          版权声明限制
          <a-typography-text mark>40</a-typography-text>
          位字符长度
        </a-typography-paragraph>
      </a-typography>
    </a-col>
  </a-row>
</template>

<style lang="less" scoped>
.sys-copyright {
  color: rgba(0, 0, 0, 0.75);
  font-size: 14px;
  font-weight: 600;
  line-height: 1.4;
  margin-bottom: 24px;
}
</style>
