<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>관리자 관리</span>
        <span>{{ pageId }}</span>
      </div>
    </div>

    <div class="view-wrap mt--45">
      <div class="view-box">
        <div class="view-box-top">
          <h3 v-if="pageType == 'I'">관리자 등록</h3>
          <h3 v-else>관리자 수정</h3>
        </div>
        <div class="view-box-btm">
          <div class="form-style1">
            <v-form ref="addForm">
              <table>
                <colgroup>
                  <col style="width: 12.5rem" />
                  <col />
                </colgroup>
                <tbody>
                  <tr v-if="useAuthStore().getCompanyId == '0-000000'">
                    <th>회사명<span class="bul">*</span></th>
                    <td>
                      <v-text-field
                        v-model="form.companyName"
                        maxlength="10"
                        class="custom-input mini"
                        style="max-width: 200px"
                        :readonly="pageType == 'U'"
                        :rules="[useValid.required('회사명')]"
                      ></v-text-field>
                    </td>
                  </tr>
                  <tr>
                    <th>아이디<span class="bul">*</span></th>
                    <td>
                      <div class="form--group--inner align-start">
                        <v-text-field
                          v-model="form.id"
                          class="custom-input mini"
                          style="max-width: 200px"
                          :readonly="isReadonly"
                          placeholder=""
                          :rules="[useValid.required('아이디')]"
                        ></v-text-field>
                        <v-btn
                          v-if="!isReadonly"
                          class="custom-btn mini btn-black"
                          @click="idCheck"
                          :class="{ disabled: form.idCheck }"
                          >중복 확인</v-btn
                        >
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>패스워드<span v-if="pageType == 'I'" class="bul">*</span></th>
                    <td>
                      <v-text-field
                        v-model="form.passWord"
                        class="custom-input mini"
                        type="password"
                        style="max-width: 200px"
                        :rules="
                          pageType == 'U'
                            ? form.passWord.length > 0
                              ? [useValid.passWordChk(form.passWord)]
                              : []
                            : [useValid.passWordChk(form.passWord)]
                        "
                      ></v-text-field>
                    </td>
                  </tr>

                  <tr>
                    <th>
                      패스워드 확인<span v-if="pageType == 'I'" class="bul">*</span>
                    </th>
                    <td>
                      <v-text-field
                        v-model="form.passWordCheck"
                        type="password"
                        class="custom-input mini"
                        style="max-width: 200px"
                        :rules="
                          pageType == 'U' && form.passWord.length == 0
                            ? []
                            : [useValid.passWordConfirm(form.passWord)]
                        "
                      ></v-text-field>
                    </td>
                  </tr>
                  <tr>
                    <th>이름<span class="bul">*</span></th>
                    <td>
                      <v-text-field
                        v-model="form.name"
                        maxlength="10"
                        :readonly="isReadonly"
                        class="custom-input mini"
                        style="max-width: 200px"
                        :rules="[useValid.required('이름')]"
                      ></v-text-field>
                    </td>
                  </tr>
                  <tr>
                    <th>연락처<span class="bul">*</span></th>
                    <td>
                      <div class="form--group--inner">
                        <v-text-field
                          v-model="form.phone[0]"
                          class="custom-input mini"
                          style="max-width: 150px"
                          maxlength="4"
                          :rules="[useValid.required('연락처')]"
                        ></v-text-field>
                        -
                        <v-text-field
                          v-model="form.phone[1]"
                          class="custom-input mini"
                          maxlength="4"
                          :rules="[useValid.required('연락처')]"
                          style="max-width: 150px"
                        ></v-text-field>
                        -
                        <v-text-field
                          v-model="form.phone[2]"
                          maxlength="4"
                          :rules="[useValid.required('연락처')]"
                          class="custom-input mini"
                          style="max-width: 150px"
                        ></v-text-field>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>이메일<span class="bul">*</span></th>
                    <td>
                      <div class="form--group--inner">
                        <v-text-field
                          v-model="form.email[0]"
                          class="custom-input mini"
                          :rules="[useValid.required('이메일')]"
                          style="width: 200px"
                        ></v-text-field>
                        @
                        <v-text-field
                          :class="{ visible: hide }"
                          v-model="form.email[1]"
                          class="custom-input mini"
                          :rules="[useValid.required('이메일')]"
                          style="width: 250px"
                        ></v-text-field>
                        <v-select
                          v-model="form.emailSet"
                          variant="outlined"
                          style="max-width: 250px"
                          class="custom-select"
                          :items="form.emailArr"
                          @update:modelValue="emailPush(form.emailSet)"
                        >
                        </v-select>
                      </div>
                    </td>
                  </tr>
                  <tr v-if="useAuthStore().getCompanyId == '0-000000'">
                    <th class="bg le">기업코드<span class="bul">*</span></th>
                    <td>
                      <div class="form--group--inner">
                        <v-text-field
                          class="custom-input mini"
                          v-model="form.companyId"
                          style="max-width: 200px"
                          :readonly="pageType == 'U'"
                        ></v-text-field>
                        <span class="caution--text fts--14"
                          >* 0-000000 형식의 자릿수 맞추어 등록(주의 : 등록 후
                          수정불가능!)</span
                        >
                      </div>
                    </td>
                  </tr>
                  <tr v-if="pageType == 'U'">
                    <th>상태<span class="bul">*</span></th>
                    <td>
                      <v-select
                        variant="outlined"
                        style="width: 250px"
                        class="custom-select"
                        v-model="form.status"
                        :items="form.statusArr"
                      >
                      </v-select>
                    </td>
                  </tr>
                </tbody>
              </table>
            </v-form>
          </div>
        </div>
      </div>

      <div class="view-btm-btn">
        <div class="btn-l">
          <v-btn class="custom-btn btn-list" @click="listLocated"
            ><i class="ico"></i>목록</v-btn
          >
        </div>
        <div class="btn-r">
          <v-btn v-show="pageType == 'I'" class="custom-btn btn-blue2" @click="fnRegCheck"
            ><i class="ico"></i>저장</v-btn
          >
          <v-btn v-show="pageType == 'U'" class="custom-btn btn-blue2" @click="fnRegCheck"
            ><i class="ico"></i>수정</v-btn
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import VueDatePicker from "@vuepic/vue-datepicker";
  import "@vuepic/vue-datepicker/dist/main.css";
  import { now } from "lodash";
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  /************************************************************************
|    전역
************************************************************************/
  const hide = ref(null);
  const addForm = ref(null);
  const router = useRouter();
  const { $eventBus } = useNuxtApp();
  const isReadonly = ref(false);
  const pageType = ref("");
  const adminId = ref("");
  const pageId = ref("");
  const datePickerFormat = "yyyy-MM-dd";
  const today = new Date().toISOString().slice(0, 10);
  const form = ref({
    companyId: "",
    companyName: "",
    id: "",
    passWord: "",
    passWordCheck: "",
    name: "",
    phone: ["", "", ""],
    email: ["", ""],
    emailSet: "직접 입력",
    emailArr: [
      { title: "직접 입력", value: "" },
      { title: "naver.com", value: "naver.com" },
      { title: "gmail.com", value: "gmail.com" },
      { title: "daum.net", value: "daum.net" },
      { title: "yahoo.com", value: "yahoo.com" },
      { title: "icloud.com", value: "icloud.com" },
      { title: "hotmail.com", value: "hotmail.com" },
      { title: "outlook.com", value: "outlook.com" },
    ],
    regDate: today,
    status: "",
    statusArr: [
      { title: "사용중", value: "0" },
      { title: "정지", value: "1" },
    ],
    idCheck: false,
  });

  const fnUpdEvt = () => {
    let param = {
      id: pageId,
      title: "관리자 수정",
      content: "저장하시겠습니까?",
      yes: {
        text: "저장",
        isProc: true,
        event: "FN_UPDATE",
        param: "",
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  };

  const fnRegCheck = () => {
    nextTick(() => {
      if (addForm.value && typeof addForm.value.validate === "function") {
        addForm.value
          .validate()
          .then((isValid) => {
            if (isValid.valid) {
              if (pageType.value == "I") {
                if (form.value.idCheck) {
                  fnRegEvt();
                }
              } else {
                fnUpdEvt();
              }
            } else {
              if (pageType.value == "I") {
                if (form.value.idCheck == false) {
                  let param = {
                    id: pageId,
                    title: "관리자 등록",
                    content: "중복 여부를 체크한 뒤 다시 시도해주세요.",
                    yes: {
                      text: "확인",
                      isProc: false,
                    },
                  };
                  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
                } else {
                  let param = {
                    id: pageId,
                    title: "관리자 등록",
                    content: "필수항목을 입력해주세요.",
                    yes: {
                      text: "확인",
                      isProc: false,
                    },
                  };
                  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
                }
              } else {
                let param = {
                  id: pageId,
                  title: "관리자 수정",
                  content: "필수항목을 입력해주세요.",
                  yes: {
                    text: "확인",
                    isProc: false,
                  },
                };
                $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
              }
            }
          })
          .catch((err) => {
            console.error("벨리데이션 에러", err);
          });
      } else {
        console.error("항목 누락체크[fnRegCheck]]");
      }
    });
  };

  const fnRegEvt = () => {
    let param = {
      id: pageId,
      title: "관리자 등록",
      content: "등록하시겠습니까?",
      yes: {
        text: "등록",
        isProc: true,
        event: "FN_INSERT",
        param: "",
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  };

  const fnInsert = () => {
    let params = {
      id: form.value.id,
      password: form.value.passWord,
      name: form.value.name,
      phone: form.value.phone[0] + "-" + form.value.phone[1] + "-" + form.value.phone[2],
      email: form.value.email[0] + "@" + form.value.email[1],
      regdate: Date.now(),
      comp_name:
        useAuthStore().getCompanyId == "0-000000"
          ? form.value.companyName
          : useAuthStore().getCompanyName,
      comp_id:
        useAuthStore().getCompanyId == "0-000000"
          ? form.value.companyId
          : useAuthStore().getCompanyId,
    };

    useAxios()
      .post("/mng/reg", params)
      .then((res) => {
        router.push("/view/mng");
      })
      .catch((error) => {
        //$log.debug("[equipMgmtReg][fnGetTenantList][error]");
        //useErrorHandler().fnSetCommErrorHandle(error, fnGetTenantList);
      })
      .finally(() => {
        //$log.debug("[equipMgmtReg][fnGetTenantList][finished]");
        //objSlt.value.tenantNameList = _cloneDeep(temp);
      });
  };

  const fnUpdate = () => {
    let params = {
      id: useDtStore.adminInfo.adminId,
      password: form.value.passWord,
      name: form.value.name,
      phone: form.value.phone[0] + "-" + form.value.phone[1] + "-" + form.value.phone[2],
      email: form.value.email[0] + "@" + form.value.email[1],
      regdate: form.value.regDate,
      status: form.value.status,
      comp_name:
        useAuthStore().getCompanyId == "0-000000"
          ? form.value.companyName
          : useAuthStore().getCompanyName,
      comp_id:
        useAuthStore().getCompanyId == "0-000000"
          ? form.value.companyId
          : useAuthStore().getCompanyId,
    };

    useAxios()
      .post("/mng/update", params)
      .then((res) => {
        window.location.reload();
      })
      .catch((error) => {})
      .finally(() => {});
  };

  const fnDetail = () => {
    let _req = {
      id: useDtStore.adminInfo.adminId,
    };
    useAxios()
      .get(`/mng/detail/${_req.id}`)
      .then((res) => {
        form.value.companyId = res.data.COMP_ID;
        form.value.companyName = res.data.COMP_NAME;
        form.value.id = res.data.ID;
        form.value.name = res.data.NAME;
        form.value.phone[0] = res.data.PHONE.split("-")[0];
        form.value.phone[1] = res.data.PHONE.split("-")[1];
        form.value.phone[2] = res.data.PHONE.split("-")[2];
        form.value.email[0] = res.data.EMAIL.split("@")[0];
        form.value.email[1] = res.data.EMAIL.split("@")[1];
        form.value.regDate = new Date(res.data.REGDATE);
        form.value.status = res.data.STATUS;
      })
      .catch((error) => {})
      .finally(() => {});
  };

  const emailPush = (__VAL) => {
    form.value.email[1] = __VAL;
    hide.value = __VAL.length > 0 ? true : false;
  };

  /************************************************************************
|    함수(METHODS)
************************************************************************/

  const listLocated = () => {
    router.push({
      path: "/view/mng",
    });
  };

  const idCheck = () => {
    let params = {
      id: form.value.id,
    };

    if (form.value.id.length > 0) {
      useAxios()
        .post("/mng/chk", params)
        .then((res) => {
          let param = {
            id: pageId,
            title: "아이디 중복체크",
            content: "사용가능한 아이디입니다.",
            yes: {
              text: "확인",
              isProc: false,
            },
          };
          $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
          form.value.idCheck = true;
        })
        .catch((error) => {
          let param = {
            id: pageId,
            title: "아이디 중복체크",
            content: "사용할 수 없는 아이디입니다.",
            yes: {
              text: "확인",
              isProc: false,
            },
          };
          $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
          form.value.idCheck = false;
          //$log.debug("[equipMgmtReg][fnGetTenantList][error]");
          //useErrorHandler().fnSetCommErrorHandle(error, fnGetTenantList);
        })
        .finally(() => {
          //$log.debug("[equipMgmtReg][fnGetTenantList][finished]");
          //objSlt.value.tenantNameList = _cloneDeep(temp);
        });
    } else {
      let param = {
        id: pageId,
        title: "아이디 중복체크",
        content: "아이디를 입력해주세요.",
        yes: {
          text: "확인",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    }
  };

  /************************************************************************
|    라이프사이클
************************************************************************/
  onMounted(() => {
    pageType.value = useDtStore.adminInfo.pageType;

    //관리자 등록/수정 분기처리
    if (pageType.value == "U") {
      adminId.value = useDtStore.adminInfo.adminId;
      pageId.value = "관리자 수정";
      isReadonly.value = true;
      fnDetail();
    } else {
      pageId.value = "관리자 등록";
    }
  });

  /************************************************************************
|    팝업 이벤트버스 정의
************************************************************************/
  $eventBus.off("FN_INSERT");
  $eventBus.on("FN_INSERT", () => {
    fnInsert();
  });
  $eventBus.off("FN_UPDATE");
  $eventBus.on("FN_UPDATE", () => {
    fnUpdate();
  });
  /************************************************************************
|    WATCH
************************************************************************/
</script>
