<template>
  <div class="wrap">
    <div class="tab-wrap">
      <ul>
        <li>
          <button class="tab active">사용자 관리</button>
        </li>
        <li>
          <button @click="accessLogPage()" class="tab">로그인 기록 조회</button>
        </li>
      </ul>
    </div>
    <div>
      <div>
        <h2 class="page-title">사용자 정보</h2>
      </div>
      <hr class="margin">
      <div class="form-wrap grid gap">
        <div class="grid2_8 ">
          <span>아이디 : </span>
          <span>{{ user.user_id }} </span>
        </div>
        <div class="grid2_8 ">
          <span>이름 : </span>
          <input type="text" placeholder="Name" v-model="user.user_nm">
        </div>
        <div class="grid2_8 ">
          <span>전화번호 : </span>
          <div class="flex gap">
            <input type="text" style="width: 7rem" maxlength="3" v-model="tel_first">
            <div>&nbsp; - &nbsp;</div>
            <input type="text" style="width: 7rem" maxlength="4" v-model="tel_second">
            <div>&nbsp; - &nbsp;</div>
            <input type="text" style="width: 7rem" maxlength="4" v-model="tel_third">
          </div>
        </div>
        <div class="grid2_8 ">
          <span>이메일 : </span>
          <div class="flex gap">
            <input type="text" style="width: 10rem" v-model="email_id">
            <div style="height: 3rem; line-height: 1rem;">&nbsp; 	&#64; &nbsp;</div>
            <input type="text" style="width: 10rem" v-model="email_domain" :disabled="email_disabled === true">
            <select @change="emailValue($event.target.value)">
              <option selected disabled>선택하세요</option>
              <option value="naver.com">naver.com</option>
              <option value="gmail.com">gmail.com</option>
              <option value="hanmail.net">hanmail.net</option>
              <option value="daum.net">daum.net</option>
              <option value="nate.com">nate.com</option>
              <option value="null">직접입력</option>
            </select>
          </div>
        </div>
        <div class="grid2_8 ">
          <span>관리구역 : </span>
          <div class="flex-between gap dongselect">
            <dongSelectList @setDongCd="setDongCd" :nodeHiddenCk="true" :crslk_azHiddenCk="true" 
            :user_sido_cd="user.user_sido_cd" :user_sigungu_cd="user.user_sigungu_cd" :user_dong_cd="user.user_dong_cd"></dongSelectList>
          </div>
        </div>
        <div class="grid2_8 ">
          <span>비고 : </span>
          <input type="text" placeholder="참고사항을 입력해주세요." v-model="user.rm">
        </div>
        <div class="grid2_8 ">
          <span>권한 : </span>
          <div class="flex gap">
            <label for="radio_1">
              <input type="radio" name="radio" id="radio_1" value="시청관리자" v-model="user.user_author">
              시청관리자
            </label>
            <label for="radio_2">
              <input type="radio" name="radio" id="radio_2" value="지자체관리자" v-model="user.user_author">
              지자체관리자
            </label>
          </div>
        </div>

        <div class="btn-wrap flex-between">
          <button type="button" class="green-btn s-btn" @click="userUpdateCheck">수정</button>
          <button type="button" class="green-btn s-btn" @click="modal_delete = true">삭제</button>
          <button type="button" class="btn-2 gray-btn s-btn" @click="userSelectListPage()">취소</button>
        </div>
        <div class="btn-wrap">
        <button type="button" class="green-btn s-btn" @click="pwReset">비밀번호 초기화</button>
      </div>
      </div>
    </div>
  </div>

  <div class="modal-wrap" v-if="modal_update == true">
    <div class="modal-bg">
    </div>
    <div class="modal">
      <p>수정하신 정보를 <span class="txt-point">저장</span>하시겠습니까?</p>
      <div class="btn-wrap">
        <button type="button" class="green-btn" @click="userUpdate">확인</button>
        <button type="button" class="gray-btn" @click="modal_update = false">취소</button>
      </div>
    </div>
  </div>

  <div class="modal-wrap"  v-if="modal_delete == true">
    <div class="modal-bg">
    </div>
    <div class="modal">
      <p>
        해당 기능은 데이터 <span class="txt-point-red">삭제</span>기능입니다.<br>
        데이터 <span class="txt-point-red">삭제</span> 후, 조회에서 해당 데이터를 확인할 수 없습니다.<br>
        <span class="txt-point-red">삭제</span>를 원하시면 아래 삭제 버튼을 눌러주세요.
      </p>
      <div class="btn-wrap">
        <button type="button" class="green-btn" @click="userDelete">삭제</button>
        <button type="button" class="gray-btn" @click="modal_delete = false">취소</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import COMMON_UTIL from '../../../resources/js/commonUtil.ts';
import { useRoute } from 'vue-router';
import dongSelectList from '../../component/dongSelectList.vue';

export default {
  data: () => {
    return {
      user: {
        user_id: null,
        user_nm: null,
        user_telno: null,
        user_eml: null,
        user_author: null,
        rm: null,
        user_sido_cd: null,
        user_sigungu_cd: null,
        user_dong_cd: null,
        pw_reset: null,
        dong_cd: null
      },
      route: useRoute(),
      
      //전화번호
      tel_first: null,
      tel_second: null,
      tel_third: null,
      
      //이메일
      email_disabled: true,
      email_id: null,
      email_domain: null,
      
      modal_update: false,
      modal_delete: false,

      //관리구역 행동코드
      address: {}
    };
  },
  methods: {

    //사용자 상세조회
    userSelectOne: function() {
      const vm = this;
      axios({
        url: '/user/userSelectOne.json',
        method: 'post',
        headers: {
          "Content-Type": "application/json; charset=UTF-8"
        },
        data: vm.route.query
      }).then(function (response) {
        // console.log("userSelectOne - response : ", response.data);
        vm.user = response.data;
        vm.tel_first = response.data.user_telno.substring(0,3);
        vm.tel_second = response.data.user_telno.substring(3,7);
        vm.tel_third = response.data.user_telno.substring(7);
        var email = response.data.user_eml.split('@');
        vm.email_id = email[0];
        vm.email_domain = email[1];
      }).catch(function(error) {
        console.log("userSelectOne - error : ", error)
      });
    },

    // 수정버튼 클릭 시 빈칸 검사
    userUpdateCheck: function() {
   
      if (COMMON_UTIL.isEmpty(this.user.user_nm) === false) {
        alert('이름을 입력해주세요.');
        return false;
      }

      if (COMMON_UTIL.isEmpty(this.tel_first) === false) {
        alert('전화번호를 입력해주세요.');
        return false;
      }

      if (COMMON_UTIL.isEmpty(this.tel_second) === false) {
        alert('전화번호를 입력해주세요.');
        return false;
      }

      if (COMMON_UTIL.isEmpty(this.tel_third) === false) {
        alert('전화번호를 입력해주세요.');
        return false;
      }

      if (COMMON_UTIL.isEmpty(this.email_id) === false) {
        alert('이메일 ID를 입력해주세요.');
        return false;
      }

      if (COMMON_UTIL.isEmpty(this.email_domain) === false) {
        alert('이메일을 선택 혹은 입력해주세요.');
        return false;
      }

      if (COMMON_UTIL.isEmpty(this.address.siDo_dong_cd) === false) {
        alert('관리구역을 선택해주세요.');
        return false;
      }

      if (COMMON_UTIL.isEmpty(this.user.user_author) === false) {
        alert('권한을 선택해주세요.');
        return false;
      }
      this.modal_update = true
    },

    userUpdate: function() {
      const vm = this;
      vm.user.user_telno = vm.tel_first + vm.tel_second + vm.tel_third;
      vm.user.user_eml = vm.email_id + '@' + vm.email_domain;
      vm.user.dong_cd = vm.address.dong_cd;
      vm.user.pw_reset = false;
      // console.log("ㅁ너ㅏ룸나ㅓ홈ㄴ",vm.user.pw_reset);
      axios({
        url: '/user/userUpdate.json',
        method: 'post',
        headers: {
          'Content-Type': "application/json; charset=UTF-8",
        },
        data: vm.user
      }).then(function(response) {
        // console.log("userUpdate - response : ",response.data);
        let result = response.data;
        if(result > 0) {
          alert("사용자 정보 수정을 완료 하였습니다.");
          vm.userSelectListPage();
        } else {
          alert("수정 실패, 관리자에게 문의해주세요.");
          vm.modal_update = false;
        }
      }).catch(function (error) {
        console.log("userUpdate - error : ", error);
        alert("사용자정보 수정 오류, 관리자에게 문의해주세요.");
        vm.modal_update = false;
      })
    },

    //비밀번호 초기화
    pwReset: function() {
      const vm = this;
      vm.user.dong_cd = vm.address.dong_cd;
      vm.user.pw_reset = true;
      axios({
        url: '/user/userUpdate.json',
        method: 'post',
        headers: {
          'Content-Type': "application/json; charset=UTF-8",
        },
        data: vm.user
      }).then(function(response) {
        // console.log("userPwReset - response : ",response.data);
        var result = response.data;
        if(result > 0) {
          alert("비밀번호 초기화를 완료 하였습니다.")
          vm.userSelectListPage();
        }
        else {
          alert("초기화 실패, 관리자에게 문의해주세요.")
          vm.modal_update = false;
        }
      }).catch(function(error) {
        console.log("userPwReset - error : ", error);
        alert("비밀번호 초기화 오류, 관리자에게 문의해주세요.")
        vm.modal_update = false;
      })
    },

    //사용자아이디 사용여부 N
    userDelete: function() {
      const vm = this;
      axios({
        url: '/user/userDelete.json',
        method: 'post',
        headers: {
          'Content-Type': "application/json; charset=UTF-8",
        },
        data: vm.user
      }).then(function(response) {
        // console.log("userUpdate - response : ",response.data);
        let result = response.data;
        if(result > 0) {
          alert("사용자 삭제를 완료 하였습니다.");
          vm.userSelectListPage();
        } else {
          alert("삭제 실패, 관리자에게 문의해주세요.");
          vm.modal_delete = false;
        }
      }).catch(function (error) {
        console.log("userUpdate - error : ", error);
        alert("사용자 삭제 오류, 관리자에게 문의해주세요.");
        vm.modal_delete = false;
      })
    },

    //이메일 도메인 자동 입력
    emailValue: function(value) {
      if(value === 'null') {
        this.email_disabled = false;
        this.email_domain = null;
      }
      else {
        this.email_disabled = true; 
        this.email_domain = value;
      }
    },

    setDongCd(value) {
      this.address = value;
    },

    //사용자 목록 페이지 이동
    userSelectListPage: function () {
      this.$router.push({ path: '/UserManagement.page'});
    },

    //접속기록조회 페이지 이동
    accessLogPage: function () {
      this.$router.push({ path: '/AccessRecord.page'});
    },
  },
  watch: {},
  computed: {},
  components: {
    dongSelectList: dongSelectList
  },
  mounted() {
    console.log("UserModifyForm mounted");
    this.userSelectOne();
  },
};
</script>

<style scoped>
.wrap {
  width: 155rem;
  margin: 100px auto;
}

.tab-wrap {
  margin-bottom: 30px;
}

.tab-wrap ul {
  display: flex;
  gap: 2rem;
}

.tab {
  display: inline-block;
  width: 20rem;
  height: 3rem;
  line-height: 3rem;
  text-align: center;
  border-radius: 5px;
  background: #fff;
  color: #949292;
  border: 1px solid #949292;
}

.tab.active {
  background: #13833b;
  color: #fff;
  border-color: #13833b;
}

h2.page-title {
  font-size: 24px;
}

hr.margin {
  margin: 30px 0;
}

.form-wrap {
  width: 52rem;
  margin: 0 auto;
}
.form-wrap > div{height: 3rem;}
.form-wrap span{text-align: left; line-height: 3rem;}
select{width: -webkit-fill-available;}
.idchk {
  margin-left: 1rem;
}

.btn-wrap {
  margin-top: 30px;
  text-align: center;
}

.btn-2 {
  display: inline-block;
  padding: 0.3rem 2rem;
  font-size: 13.333px;
  color: #000;
}

.btn-wrap>*:not(:last-child) {
  margin-right: 2rem;
}

.form-wrap .flex span {
  display: inline-block;
  width: 10rem;
  padding: 0 5px;
}

.form-wrap input:not([type="radio"]) {
  width: 24.7rem;
}

/* .form-wrap select {
  min-width: 9rem;
} */

.form-wrap select:not(:last-child) {
  margin-right: 1.5rem;
}

.form-wrap input[type="radio"] {
  vertical-align: middle;
}

.form-wrap label:not(:last-child) {
  margin-right: 2rem;
}

.modal-wrap {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.modal-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .6);
}

.modal {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 350px;
  padding: 5rem;
  z-index: 2;
  background-color: #fff;
  border-radius: 1rem;
  text-align: center;
}

.modal .btn-wrap {
  margin-top: 15px;
  text-align: center;
}
.txt-point {
  color: #13833b;
}

.txt-point-red {
  color: red;
}
</style>