<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>{{ pageId }}</span>
        <span v-if="pageIdSub">{{ pageIdSub }}</span>
      </div>
    </div>
    <div class="data--list--wrap">
      <div class="table--wrap">
        <di class="table--t">
          <h3>기 발행 주식 수</h3>
        </di>
        <table>
          <colgroup>
            <col width="20%" />
            <col width="80%" />
          </colgroup>
          <tbody>
            <tr>
              <th class="bg le">주식 수<span class="bul">*</span></th>
              <td>
                <v-text-field
                  maxlength="13"
                  @input="(e) => formatNumber(e, 'formValue1')"
                  v-model="form.formValue1"
                  style="width: 300px"
                  class="custom-input mini left"
                  placeholder="주식 수를 입력하세요"
                ></v-text-field>
              </td>
            </tr>
            <tr>
              <th class="bg le">
                발행 주식 수 기준 일자(현재)<span class="bul">*</span>
              </th>
              <td>
                <div class="calendar-wrap ml--0">
                  <div class="calendar">
                    <VueDatePicker
                      :format="datePickerFormat"
                      v-model="form.formValue2"
                      auto-apply="true"
                      week-start="0"
                    ></VueDatePicker>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="table--wrap">
        <di class="table--t">
          <h3>주주구성</h3>
        </di>
        <table>
          <colgroup>
            <col width="20%" />
            <col width="80%" />
          </colgroup>
          <tbody>
            <tr>
              <th class="bg le">최대주주 및 특수 관계인<span class="bul">*</span></th>
              <td>
                <div class="input--wrap">
                  <v-text-field
                    maxlength="10"
                    style="width: 300px"
                    v-model="form.formValue3"
                    @input="(e) => formatNumber(e, 'formValue3')"
                    class="custom-input mini left"
                    placeholder="비율을 입력하세요"
                  ></v-text-field>
                  <span>%</span>
                </div>
              </td>
            </tr>
            <tr>
              <th class="bg le">기관<span class="bul">*</span></th>
              <td>
                <div class="input--wrap">
                  <v-text-field
                    maxlength="10"
                    style="width: 300px"
                    v-model="form.formValue4"
                    @input="(e) => formatNumber(e, 'formValue4')"
                    class="custom-input mini left"
                    placeholder="비율을 입력하세요"
                  ></v-text-field>
                  <span>%</span>
                </div>
              </td>
            </tr>
            <tr>
              <th class="bg le">외국인<span class="bul">*</span></th>
              <td>
                <div class="input--wrap">
                  <v-text-field
                    maxlength="10"
                    style="width: 300px"
                    @input="(e) => formatNumber(e, 'formValue5')"
                    v-model="form.formValue5"
                    class="custom-input mini left"
                    placeholder="비율을 입력하세요"
                  ></v-text-field>
                  <span>%</span>
                </div>
              </td>
            </tr>
            <tr>
              <th class="bg le">자사주<span class="bul">*</span></th>
              <td>
                <div class="input--wrap">
                  <v-text-field
                    maxlength="10"
                    style="width: 300px"
                    v-model="form.formValue6"
                    @input="(e) => formatNumber(e, 'formValue6')"
                    class="custom-input mini left"
                    placeholder="비율을 입력하세요"
                  ></v-text-field>
                  <span>%</span>
                </div>
              </td>
            </tr>
            <tr>
              <th class="bg le">기타<span class="bul">*</span></th>
              <td>
                <div class="input--wrap">
                  <v-text-field
                    maxlength="10"
                    v-model="form.formValue7"
                    @input="(e) => formatNumber(e, 'formValue7')"
                    style="width: 300px"
                    class="custom-input mini left"
                    placeholder="비율을 입력하세요"
                  ></v-text-field>
                  <span>%</span>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="view-btm-btn">
        <div class="btn-l"></div>
        <div class="btn-r">
          <v-btn class="custom-btn btn-blue2" @click="fnUpdEvt"
            ><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";
/************************************************************************
|    레이아웃
************************************************************************/
definePageMeta({
  layout: "default",
});

/************************************************************************
|   PROPS
 ************************************************************************/
const props = defineProps({
  propsData: {
    type: Object,
    default: () => {},
  },
});

/************************************************************************
|    스토어
 ************************************************************************/
const useDtStore = useDetailStore();
/************************************************************************
|    전역
 ************************************************************************/
const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
const router = useRouter();
const pageId = ref("기업경영구조");
const pageIdSub = ref();
const datePickerFormat = "yyyy-MM-dd";
const form = ref({
  formValue1: "",
  formValue2: "",
  formValue3: "",
  formValue4: "",
  formValue5: "",
  formValue6: "",
  formValue7: "",
});

/* eslint-disable */
/* prettier-ignore */

/************************************************************************
|    함수(METHODS)
************************************************************************/
const formatNumber = (event, key) => {
  let formattedInput = "";
  // 숫자만 남기기
  const input = event.target.value.replace(/[^0-9.]/g, '');
  // 3자리마다 쉼표 추가
  formattedInput = input;
  if(key == 'formValue1'){
    formattedInput = new Intl.NumberFormat().format(input);
  }
  // 실시간으로 업데이트
  form.value[key] = String(formattedInput);
};

const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = ("0" + (d.getMonth() + 1)).slice(-2);
  const day = ("0" + d.getDate()).slice(-2);
  return `${year}-${month}-${day}`;
};

const fnUpdate = () => {
  let wterGet = localStorage.getItem("tempAccess");
  let _req = {
    wter: wterGet,
    shar_count: form.value.formValue1,
    iss_shar_stan_date: form.value.formValue2,
    major_shar: form.value.formValue3,
    corp_inve: form.value.formValue4,
    fogn_inve: form.value.formValue5,
    repu_shar: form.value.formValue6,
    etc_shar: form.value.formValue7,
  };

  _req = Object.fromEntries(
    Object.entries(_req).map(([key, value]) => [
      key,
      typeof value === "string"
        ? value.replace(/,/g, "") // 문자열인 경우에만 replace
        : value == null
        ? "" // null 또는 undefined 값은 빈 문자열로 처리
        : String(value), // 그 외 값은 문자열로 변환
    ])
  );

  console.error(_req);

  useAxios()
    .post("/bm/ins", _req)
    .then((res) => {
      window.location.reload();
    })
    .catch((error) => {});
};

const fnDetail = () => {
  let _req = {};

  useAxios()
    .post("/bm/detail", _req)
    .then((res) => {
      console.error(res.data);
      // const formattedData = Object.fromEntries(
      //   Object.entries(res.data).map(([key, value]) => {
      //     let formattedValue = null;
      //     // 연도는 쉼표 제거, 금액은 쉼표 추가
      //     if(key !== shar_count){
      //       formattedValue = !isNaN(value)
      //       ? new Intl.NumberFormat().format(Number(value))
      //       : value;
      //     } else {
      //       formattedValue = value;
      //     }
      //     return [key, formattedValue];
      //   })
      // );
      // res.data = formattedData;
      // console.error(formattedData)

      form.value.formValue1 = new Intl.NumberFormat().format(res.data.shar_count);

      form.value.formValue2 = res.data.iss_shar_stan_date;
      form.value.formValue3 = res.data.major_shar; //최대주주
      form.value.formValue4 = res.data.corp_inve; //기관
      form.value.formValue5 = res.data.fogn_inve; //외국인
      form.value.formValue6 = res.data.repu_shar; //자사주
      form.value.formValue7 = res.data.etc_shar; //기타
    })
    .catch((error) => {});
};

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);
};

$eventBus.off("FN_UPDATE");
$eventBus.on("FN_UPDATE", () => {
  fnUpdate();
});

/************************************************************************
|    WATCH
************************************************************************/
watch(
  () => form.value.formValue2,
  (newVal) => {
    if (newVal) {
      form.value.formValue2 = formatDate(newVal);
    }
  }
);

onMounted(() => {
  fnDetail();
});
</script>
