<!--
  Program: Terms Conditions Detail
  Author: SDL
  Brief: Use Terms and Conditions Detailed Page
-->
<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>

    <table class="table table-bordered ui--table-form ui--table-form-view mb-0">
      <colgroup>
        <col style="width: 12.5%" />
        <col style="width: 35.5%" />
        <col style="width: 12.5%" />
        <col style="width: 35.5%" />
      </colgroup>
      <tbody>
        <tr>
          <th class="text-nowrap" scope="row">
            {{ $t('sdl.privacyPolicy.part') }}
            <span class="ui--text-required" v-show="viewMode !== 'detail'">*</span>
          </th>
          <td>
            <span class="form-control-plaintext" v-if="viewMode === 'detail'">{{ getLabel(term.termsCode) }}</span>
            <select v-else class="form-select w-auto" v-model="term.partId">
              <option v-for="item in terms" :key="item.codeId" :value="item.codeId">{{ getLabel(item) }}</option>
            </select>
          </td>
          <th class="text-nowrap" scope="row">
            {{ $t('sdl.privacyPolicy.language') }}
            <span class="ui--text-required" v-show="viewMode !== 'detail'">*</span>
          </th>
          <td>
            <span v-if="viewMode === 'detail'" class="form-control-plaintext">{{ getLabel(term.langTypeCode) }}</span>
            <select v-else class="form-select w-auto" v-model="term.langType">
              <option v-for="lang in termsLang" :key="lang.code" :value="lang.code">{{ getLabel(lang) }}</option>
            </select>
          </td>
        </tr>

        <tr>
          <th class="text-nowrap" scope="row">
            {{ $t('sdl.privacyPolicy.label.agreeUsed') }}
            <span class="ui--text-required" v-show="viewMode !== 'detail'">*</span>
          </th>
          <td>
            <span v-if="viewMode === 'detail'" class="form-control-plaintext">
              {{ term.agreePage ? $t('sdl.common.label.use') : $t('sdl.common.label.nonUse') }}
            </span>
            <div class="d-block w-100" v-else>
              <div class="form-check form-check-inline">
                <input id="agreePageY" class="form-check-input" type="radio" name="agreePage" v-model="term.agreePage" :value="true" @change="changeCheck()" />
                <label for="agreePageY" class="form-check-label">{{ $t('sdl.common.label.use') }}</label>
              </div>
              <div class="form-check form-check-inline">
                <input id="agreePageN" class="form-check-input" type="radio" name="agreePage" v-model="term.agreePage" :value="false" @change="changeCheck()" />
                <label for="agreePageN" class="form-check-label">{{ $t('sdl.common.label.nonUse') }}</label>
              </div>
            </div>
          </td>
          <th class="text-nowrap" scope="row">
            {{ $t('sdl.privacyPolicy.label.checkLabel') }}
            <span class="ui--text-required" v-show="viewMode !== 'detail' && term.agreePage">*</span>
          </th>
          <td>
            <span v-if="viewMode === 'detail'" class="form-control-plaintext">
              {{ term.checkLabel }}
            </span>
            <input v-else type="text" class="form-control" v-model="term.checkLabel" placeholder-no="이용에 동의합니다" />
          </td>
        </tr>
        <tr>
          <th class="text-nowrap" scope="row">
            {{ $t('sdl.privacyPolicy.label.mandatory') }}
            <span class="ui--text-required" v-show="viewMode !== 'detail' && term.agreePage === true">*</span>
          </th>
          <td>
            <span v-if="viewMode === 'detail'" class="form-control-plaintext">
              {{ term.agreeReq ? $t('sdl.privacyPolicy.mandatory') : $t('sdl.privacyPolicy.choice') }}
            </span>
            <div class="d-block w-100" v-else>
              <div class="form-check form-check-inline">
                <input id="agreeReqY" class="form-check-input" type="radio" name="agreeReq" v-model="term.agreeReq" :value="true" @change="changeCheck()" />
                <label for="agreeReqY" class="form-check-label">{{ $t('sdl.privacyPolicy.mandatory') }}</label>
              </div>
              <div class="form-check form-check-inline">
                <input id="agreeReqN" class="form-check-input" type="radio" name="agreeReq" v-model="term.agreeReq" :value="false" @change="changeCheck()" />
                <label for="agreeReqN" class="form-check-label">{{ $t('sdl.privacyPolicy.choice') }}</label>
              </div>
            </div>
          </td>
          <th class="text-nowrap" scope="row">
            {{ $t('sdl.privacyPolicy.label.checkMsg') }}
            <span class="ui--text-required" v-show="viewMode !== 'detail' && term.agreeReq">*</span>
          </th>
          <td>
            <span v-if="viewMode === 'detail'" class="form-control-plaintext">
              {{ term.checkMsg }}
            </span>
            <input v-else type="text" class="form-control" v-model="term.checkMsg" placeholder-no="동의하지 않은 항목이 있습니다" />
          </td>
        </tr>
        <tr>
          <th class="text-nowrap" scope="row">{{ $t('sdl.privacyPolicy.policyPage') }}<span class="ui--text-required" v-show="viewMode !== 'detail'">*</span></th>
          <td>
            <span v-if="viewMode === 'detail'" class="form-control-plaintext">
              {{ term.policyPage ? $t('sdl.common.label.use') : $t('sdl.common.label.nonUse') }}
            </span>
            <div class="d-block w-100" v-else>
              <div class="form-check form-check-inline">
                <input id="policyPageY" class="form-check-input" type="radio" name="policyPage" v-model="term.policyPage" :value="true" />
                <label for="policyPageY" class="form-check-label">{{ $t('sdl.common.label.use') }}</label>
              </div>
              <div class="form-check form-check-inline">
                <input id="policyPageN" class="form-check-input" type="radio" name="policyPage" v-model="term.policyPage" :value="false" />
                <label for="policyPageN" class="form-check-label">{{ $t('sdl.common.label.nonUse') }}</label>
              </div>
            </div>
          </td>
          <th class="text-nowrap" scope="row">
            {{ $t('sdl.common.label.enforcementDate') }}
            <span class="ui--text-required" v-show="viewMode !== 'detail'">*</span>
          </th>
          <td>
            <span v-if="viewMode === 'detail'" class="form-control-plaintext">
              {{ $filters.dateFormat(convertDate(term.startDate)) }}
            </span>
            <sdl-datepicker v-else v-model="term.startDate" @moment="updateDate"></sdl-datepicker>
          </td>
        </tr>
        <tr v-if="viewMode === 'detail'">
          <th class="text-nowrap" scope="row">{{ $t('sdl.privacyPolicy.createUser') }}</th>
          <td>
            {{ term.firstRegrName }}
          </td>
          <th class="text-nowrap" scope="row">{{ $t('sdl.privacyPolicy.createDate') }}</th>
          <td>
            {{ $filters.dateFormat(term.firstRegDatetime) }}
          </td>
        </tr>
        <tr v-if="viewMode === 'detail'">
          <th class="text-nowrap" scope="row">{{ $t('sdl.privacyPolicy.updateUser') }}</th>
          <td>
            {{ term.lastModrName }}
          </td>
          <th class="text-nowrap" scope="row">{{ $t('sdl.privacyPolicy.updateDate') }}</th>
          <td>
            {{ $filters.dateFormat(term.lastModDatetime) }}
          </td>
        </tr>
        <tr v-if="viewMode === 'detail' && term.mailForm && term.mailForm !== ''">
          <th class="text-nowrap" scope="row">{{ $t('sdl.privacyPolicy.noticeMailForm') }}</th>
          <td colspan="3">
            <!--            <a href="javascript:" @click="previewMailForm">PreView</a>-->
            <button class="btn btn-outline-secondary ui--btn-xs" @click="previewMailForm">PreView</button>
          </td>
        </tr>
        <tr v-if="viewMode !== 'detail'">
          <th class="text-nowrap" scope="row">{{ $t('sdl.privacyPolicy.noticeMailForm') }}</th>
          <td colspan="3">
            <span v-if="term.mailForm && term.mailForm !== ''" class="me-2">
              <!--              <a href="javascript:" @click="previewMailForm">PreView</a>-->
              <button class="btn btn-outline-secondary ui--btn-xs" @click="previewMailForm">PreView</button>
            </span>
            <input type="file" class="form-control" accept=".html" ref="mailFile" />
          </td>
        </tr>
      </tbody>
    </table>
    <article class="ui--viewer" v-if="viewMode === 'detail'" v-html="$filters.nl2br(term.content)"></article>
    <article class="mt-3 mb-4" v-else>
      <textarea style="width: 100%; overflow: scroll; height: 250px; max-height: 250px" class="form-control" v-model="term.content"></textarea>
    </article>

    <div class="ui--button-container" v-if="viewMode === 'new'">
      <button class="btn btn-secondary btn-lg" type="submit" @click="goBackToList">
        {{ $t('sdl.common.label.cancel') }}
      </button>
      <button class="btn btn-primary btn-lg" type="submit" @click="save">{{ $t('sdl.common.label.save') }}</button>
    </div>
    <div class="ui--button-container" v-if="viewMode === 'detail'">
      <button class="btn btn-secondary btn-lg" type="submit" @click="goBackToList">
        {{ $t('sdl.common.label.list') }}
      </button>
      <button class="btn btn-secondary btn-lg" type="submit" @click="goEdit">{{ $t('sdl.common.label.edit') }}</button>
      <button class="btn btn-primary btn-lg" type="submit" v-show="term.mailForm" @click="sendEmail">
        {{ $t('sdl.email.delivery') }}
      </button>
    </div>
    <div class="ui--button-container" v-if="viewMode === 'edit'">
      <button class="btn btn-secondary btn-lg" type="submit" @click="goDetail">
        {{ $t('sdl.common.label.cancel') }}
      </button>
      <button class="btn btn-primary btn-lg" type="submit" @click="save">{{ $t('sdl.common.label.save') }}</button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import axios from 'axios';
import moment from 'moment';
import StoreParams from '@/mixin/StoreParams';
import SDLLocale from '@/mixin/SDLLocale';
import SDLUtil from '@/utils/SDLUtil';
import TermsPreviewPopup from './TermsPreviewPopup.vue';

export default {
  mixins: [SDLLocale, StoreParams],
  data() {
    return {
      viewMode: '',
      termId: '',
      defaultTerm: {
        content: '',
        checkLabel: '',
        checkMsg: '',
        startDate: '',
        agreeReq: false,
        agreePage: false,
        policyPage: false,
      },
      term: {
        ...this.defaultTerm,
        termsCode: {},
        langTypeCode: {},
      },
      terms: [], // partId list
      termsLang: [],
    };
  },
  computed: {
    ...mapGetters({
      menus: 'getMenus',
    }),
  },
  methods: {
    goEdit() {
      this.$router.push({ path: `${this.$CONTEXT}/admin/etc/terms-conditions/edit/${this.termId}` });
    },
    goDetail() {
      this.$router.push({ path: `${this.$CONTEXT}/admin/etc/terms-conditions/detail/${this.termId}` });
    },
    save() {
      // validation
      let alertMsg = '';
      const { agreePage, agreeReq, checkLabel, checkMsg, startDate, content } = this.term;

      if (agreePage && checkLabel.trim() === '') {
        // whether consent is used
        alertMsg = 'sdl.privacyPolicy.valid.checkLabel';
      } else if (agreeReq && checkMsg.trim() === '') {
        // mandatory
        alertMsg = 'sdl.privacyPolicy.valid.checkMsg';
      } else if (startDate === '') {
        // enforcement date
        alertMsg = 'sdl.privacyPolicy.valid.startDate';
      } else if (content === '') {
        // content
        alertMsg = 'sdl.privacyPolicy.valid.content';
      }

      if (alertMsg !== '') {
        SDLUtil.alert(alertMsg);
        return;
      }

      SDLUtil.confirm({
        msg: 'sdl.common.message.doSave',
        title: 'sdl.common.label.save',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => {
          SDLUtil.showLoadingBar(true);
          // this.term
          const param = {
            partId: this.term.partId,
            langType: this.term.langType,
            checkLabel: this.term.checkLabel,
            checkMsg: this.term.checkMsg,
            startDate: this.term.startDate,
            policyPage: this.term.policyPage,
            agreePage: this.term.agreePage,
            agreeReq: this.term.agreeReq,
            content: this.term.content,
          };
          if (this.viewMode !== 'new') {
            param.termsId = this.termId;
          }

          const form = SDLUtil.formParameters(param);

          const { mailFile } = this.$refs;
          if (mailFile.files.length > 0) {
            form.append('mailFile', mailFile.files[0]);
          }

          let url = `${SDLUtil.API_URL}/privacypolicy/terms`;
          if (this.viewMode === 'edit') {
            url += `/${this.termId}`;
          }

          axios
            .post(url, form, {
              headers: {
                'Content-Type': 'multipart/form-data',
              },
            })
            .then(({ data }) => {
              // console.info('success', data);
              SDLUtil.showLoadingBar(false);
              if (this.viewMode === 'new') {
                this.$router.replace({
                  path: `${SDLUtil.WEB_CONTEXT_PATH}/admin/etc/terms-conditions/detail/${data.termsId}`,
                });
              } else {
                this.$router.replace({
                  path: `${SDLUtil.WEB_CONTEXT_PATH}/admin/etc/terms-conditions/detail/${this.termId}`,
                });
              }
            })
            .catch(err => {
              SDLUtil.errorAlert(err);
              SDLUtil.showLoadingBar(false);
            });
        },
      });
    },
    getTerm() {
      // axios.get('/static/dummy/termInfo.json').then(({ data }) => {
      axios.get(`${SDLUtil.API_URL}/privacypolicy/terms/${this.termId}`).then(({ data }) => {
        this.term = { ...this.defaultTerm, ...data };
      });
    },
    init() {
      const { path, params } = this.$route;
      if (path.startsWith(`${SDLUtil.WEB_CONTEXT_PATH}/admin/etc/terms-conditions/new`)) {
        this.viewMode = 'new';
        this.termId = '';
        this.term = {
          ...this.defaultTerm,
          partId: this.terms[0].codeId,
          langType: this.termsLang[0].code,
        };
      } else if (path.startsWith(`${SDLUtil.WEB_CONTEXT_PATH}/admin/etc/terms-conditions/edit`)) {
        this.viewMode = 'edit';
        this.termId = params.termId;
      } else if (path.startsWith(`${SDLUtil.WEB_CONTEXT_PATH}/admin/etc/terms-conditions/detail`)) {
        this.viewMode = 'detail';
        this.termId = params.termId;
      }

      if (this.viewMode !== 'new') {
        this.getTerm();
      }
    },
    changeCheck() {
      // console.info('term', this.term);
      if (this.term.policyPage === false) {
        // this.term.agreePage = false;
        // this.term.agreeReq = false;
      } else if (this.term.agreePage === false) {
        // this.term.agreeReq = false;
      }
    },
    updateDate(startDate) {
      // console.info('updateDate', startDate.format('YYYY-MM-DD'));
      this.term.startDate = startDate.format('YYYY-MM-DD');
    },
    convertDate(dateStr) {
      return moment(dateStr).format('YYYY-MM-DD');
    },
    sendEmail() {
      SDLUtil.alert('각 시스템 정책에 맞게 수정하여 사용하세요.');
    },
    previewMailForm() {
      // console.info(this.term.mailForm);
      SDLUtil.show(
        TermsPreviewPopup,
        {
          content: this.term.mailForm,
        },
        {
          width: 1000,
          height: 850,
        },
      );
    },
  },
  watch: {
    $route() {
      this.init();
    },
  },
  created() {
    this.terms = SDLUtil.getCommCodeList({ commCodeTypeId: 'TERMS' });
    this.termsLang = SDLUtil.getCommCodeList({ commCodeTypeId: 'TERMS_LANG' });
    this.init();
  },
};
</script>

<style scoped>
.form-check-input:disabled ~ .form-check-label {
  color: #212529 !important;
}
</style>
