<script setup lang="ts">
import {getDetailPrcs, updatePrice, deletePrcsFile} from '/src/service/priceApi'
import {type iPbAtt, type Person} from '/@src/utils/types'
import {formatBizNum, formatDatefromString} from "/@src/utils/common/comfunc.ts";
const notyf = useNotyf()
const loading = ref(false)
const router = useRouter()

onBeforeMount(async ()=>{
  const result = await getDetailPrcs(history.state.key)
  getDetailList(result)
})

const showTable = ref(false)
const detailActionsOpen = ref(false)

const generalParams = reactive({
  title: "",
  content: "",
  regSdat: "",
  regEdat: "",
  prvYn: true,
  prvRsn : "",
  prvPwd : "",
  aiYn: true,
})
const params = reactive({
  cateSelect: '',
  prcsNo: '',
  stCd: '', //상태코드 등록 전 : 0000
  defaultPricePerson:[],
  prcsAttsColumn:[ //첨부파일 입력
    { key: 'logiFnm', label: '구분'},
    { key: 'data', label: '데이터'}
  ],
  prcsAtts: [], //첨부파일 데이터
  felxColumn: [
    { key: 'gubunCd', label: '구분'},
    { key: 'deptNm', label: '부서' },
    { key: 'sabun', label: '사번' },
    { key: 'name', label: '이름' },
    { key: 'attendCd', label: '근태'},
    { key: 'apprStat', label: '결재상태'},
    { key: 'apprDt', label: '승인일자'},
    {key:'actions', label: '동작'},
  ],
  priceData:[],
  prcsBizsColumn: [ //견적사 입력
    { key: 'num', label: '구분', width: '10%' },
    { key: 'email', label: '이메일', editable: true, width: '50px' },
    { key: 'bizNo', label: '사업자번호', editable: true},
    { key: 'actions', label: '동작', width: '100px'}
  ],
  prcsBizs: [], //견적사 입력 데이터
  dtlSpecsColumn: [
    { key: 'num', label: '번호', editable: false },
    { key: 'itemNm', label: '품명', editable: true },
    { key: 'spec', label: '규격', editable: true },
    { key: 'unit', label: '단위', editable: true },
    { key: 'qty', label: '수량', editable: true },
    { key: '', label: '단가(VAT별도)', editable: false },
    { key: '', label: '금액(VAT별도)', editable: false },
    { key: 'delete', label: '삭제', editable: false },
  ],
  dtlSpecs: [], //상세 규격 입력 데이터
  btnChangeFlag: false
})

const pbAtts = ref<iPbAtt[]>(params.prcsAtts)

function getDetailList(arg){
  console.log("arg res",arg)
  params.prcsNo = arg.prcsNo
  params.stCd = arg.stCd
  params.cateSelect = arg.cateCd
  generalParams.title = arg.title
  generalParams.content = arg.content
  params.prcsBizs = arg.prcsBizs.map(req => ({
    bizNo: req.bizNo,
    email: req.email,
  }))
  params.dtlSpecs = arg.dtlSpecs
  generalParams.regSdat = arg.regSdat
  generalParams.regEdat = arg.regEdat
  apprLine.value = arg.apprMst.apprReqs.map(req => ({
    gubunCd: req.gubunCd,
    gubunNm: req.gubunNm,
    deptCd: req.deptCd,
    deptNm: req.deptNm,
    sabun: req.sabun,
    name: req.name,
    apprNo: req.apprNo,
    apprOrd: req.apprOrd,
    apprStat: req.apprStat,
    apprDt: req.apprDt ? req.apprDt : '-',
    attendCd: req.attendCd
  }))
  params.prcsAtts = arg.prcsAtts
}

const changeButton = () => {
  //todo 상세 규격 api 테우기
  params.btnChangeFlag = true
  close()
}

const validation = () => {
  notyf.dismissAll()
  if(generalParams.regSdat > generalParams.regEdat){
    notyf.error("등록 종료일은 등록 시작일보다 빠를 수 없습니다.")
    return false
  }

  const resultGu = apprLine.value.filter((item,index)=> index != 0 && !item.gubunCd)

  if(resultGu.length > 0){
    console.log("resultGu",resultGu)
    notyf.error("결재선 구분값을 입력해주세요")
    return false
  }

  if(apprLine.value.length < 2){
    notyf.error("결재선은 본인 외 2명이상 필수입니다.")
    return false
  }
  const result = apprLine.value.filter((item)=> item.gubunCd === '0200' )

  if(result.length > 1){
    notyf.error("결재는 한 명입니다.")
    return false
  }
  const resultLastItem = apprLine.value[apprLine.value.length-1].gubunCd
  if(resultLastItem != '0200'){
    notyf.error("결재선의 마지막은 결재자이어야 함")
    return false
  }
  return true
}

const selectUser = ref<Person[]>([])
const apprLine = ref<Person[]>([])

const isDuplicate = (person: Person) =>
    apprLine.value.some((p) => p.sabun === person.sabun)

watch(
    selectUser,
    (newPersons) => {
      if (Array.isArray(newPersons) && newPersons.length > 0) {
        const filtered = newPersons.filter((p) => !isDuplicate(p))
        apprLine.value = [...apprLine.value, ...filtered]
        selectUser.value = []
      }
    },
    { deep: true }
)

const updatePriceOne = async () => {
  let res = null
  try{
    loading.value = true
    if (validation()){
      const paramsPrice ={
        prcsNo : params.prcsNo,
        cateCd : params.cateSelect,
        title: generalParams.title,
        content: generalParams.content,
        regSdat: formatDatefromString(generalParams.regSdat),
        regEdat: formatDatefromString(generalParams.regEdat),
        prvYn: false,
        prvRsn : "",
        prvPwd : "",
        aiYn: false,
        prcsBizs: params.prcsBizs.map(({ num, ...rest }) => rest), //견적사 입력 데이터
        dtlSpecs: [], //todo
        // params.dtlSpecs.map(({ num, ...rest }) => rest), //상세 규격 입력 데이터
        prcsAtts: pbAtts.value.map(req => ({
          logiFnm: req.logiFnm,
          data: req.data})),//첨부파일 데이터,
        apprReqs: apprLine.value.map(({ deptNm, ...rest }, index) =>  ({
          ...rest,
          apprOrd: index + 1, // 결재 순서 1부터 시작
        })),  //결재선 데이터
      }
      res = await updatePrice(paramsPrice)
      notyf.dismissAll()
      if(res.request.status == '200'){
        notyf.primary('수정 되었습니다.')
        router.push({path: '/app/priceManagement'})
      }
    }
  }catch(e){
    notyf.error(e.message)
  }finally {
    loading.value = false
  }
}
const addNewEstimateRow = () => {
  const newRow = {}
  params.prcsBizsColumn.forEach(col => {
    if (col.key && col.key !== 'actions') {
      newRow[col.key] = ''
    }
  })
  params.prcsBizs.push(newRow)
}

const onDelete = (index: number) => {

  if(params.prcsBizs.length-1 !== params.prcsBizsColumn.length
      || (params.prcsBizsColumn.length == 4 && params.prcsBizs.length-1 == params.prcsBizsColumn.length))
  {
    params.prcsBizs.splice(index, 1)
  }
}

const addNewDetailRow = () => {
  const newRow = {}
  params.dtlSpecsColumn.forEach(col => {
    if (col.key) {
      newRow[col.key] = ''
    }
  })
  params.dtlSpecs.push(newRow)
  console.log(params.dtlSpecs.length)
}

const onDetailDelete = (index: number) => {

  if(params.dtlSpecs.length-1 !== params.dtlSpecsColumn.length
      || (params.dtlSpecsColumn.length == 8 && params.dtlSpecs.length-1 == params.dtlSpecsColumn.length))
  {
    params.dtlSpecs.splice(index, 1)
  }
}

const onPriceDelete = (index: number) => {

  if(apprLine.value.length-1 !== params.felxColumn.length
      || (params.felxColumn.length == 8 && apprLine.value.length-1 == params.felxColumn.length))
  {
    apprLine.value.splice(index, 1)
  }
}

function onInput(row, column){
  if (column.key === 'bizNo') {
    const raw =row[column.key].replace(/\D/g, '')
    row[column.key] = formatBizNum(raw)
  }
}

const onFileClick = () => {
  const input = <any> document.querySelector('.file-input')
  input.click()
}

const onFileChange = (e: any) => {
  Array.from(e.target.files).forEach((file: any) => {
    const reader = new FileReader()
    reader.onload = () => {
      const result = <string>reader.result
      const pbAtt = <iPbAtt>{
        prcsNo: params.prcsNo,
        logiFnm: file.name,
        size: file.size,
        data: result.split(',')[1],
      }
      notyf.dismissAll()
      if(pbAtt.logiFnm.includes('.pdf')) { //todo 여러개 올릴 때 이슈 발생 확인 필요
        pbAtts.value.push(pbAtt)
      }else{
        notyf.error("pdf 파일만 업로드 가능합니다.")
      }
    }

    reader.readAsDataURL(file)
  })
}

const onFilDelete = async (prcsNo: string, index: number, fileOrd: number) => {
  notyf.dismissAll()
  const confirmed = confirm('삭제하시겠습니까?')
  if (!prcsNo) {
    if (confirmed){
      pbAtts.value.splice(index, 1)
    }
  } else {
    if (confirmed) {
      await deletePrcsFile(prcsNo, fileOrd).then((res: string) => {
        notyf.success(res)
        pbAtts.value.splice(index, 1)
      }).catch((err) => {
        notyf.error('삭제 중 오류가 발생했습니다.')
        console.error(err)
      })
    }
  }
}

const onPrcsFileDownload = async (prcsNo: string, fileOrd: number, logiFnm: string) => {
  const link = document.createElement('a')
  link.href = `https://svcm.hmsn.ink/api/prcs/${prcsNo}/${fileOrd}` //todo
  link.setAttribute('download', logiFnm)
  link.setAttribute('target', '_blank')
  document.body.appendChild(link)
  link.click()
}

const moveUp = (index: number) => {
  if (index <= 0) return
  let temp = apprLine.value[index]
  apprLine.value[index] = apprLine.value[index - 1]
  apprLine.value[index - 1] = temp
}

const moveDown = (index: number) => {
  if (index >= apprLine.value.length - 1) return
  let temp = apprLine.value[index]
  apprLine.value[index] = apprLine.value[index + 1]
  apprLine.value[index + 1] = temp
}

</script>

<template>
  <div class="page-content is-navbar-lg">
    <div class="datatable-wrapper">
      <div class="table-container">
        <table class="table datatable-table is-fullwidth">
          <colgroup>
            <col style="width: 10%;">
            <col style="width: 10%;">
            <col style="width: 10%;">
            <col style="width: 10%;">
            <col style="width: 10%;">
            <col style="width: 10%;">
            <col style="width: 10%;">
            <col style="width: 10%;">
            <col style="width: 10%;">
            <col style="width: 10%;">
          </colgroup>
          <tbody>
          <tr>
            <td>분야<span style="color: red">*</span></td>
            <td colspan="2">
                <span class="column is-7">
                  <VField class="pr-2">
                    <VCodeSelect
                        cd_grp=5
                        v-model="params.cateSelect"/>
                  </VField>
                </span>
            </td>
            <td>제목<span style="color: red">*</span></td>
            <td colspan="6">
              <div class="column is-fullhd">
                <VField class="pr-2">
                  <VControl>
                    <input
                        v-model="generalParams.title"
                        class="input custom-text-filter"
                        placeholder="제목"
                    >
                  </VControl>
                </VField>
              </div>
            </td>
          </tr>
          <tr>
            <td>내용<span style="color: red">*</span></td>
            <td colspan="10">
              <div class="column is-fullhd">
                <VField class="pr-2">
                  <VControl>
                      <textarea
                          v-model="generalParams.content"
                          class="input custom-text-filter"
                          rows="2"
                          style="height: 100px;"
                          placeholder="내용"
                      />
                  </VControl>
                </VField>
              </div>
            </td>
          </tr>
          <tr>
            <td>견적요청<span style="color: red">*</span></td>
            <td colspan="9">
              <VButton
                  color="primary"
                  icon="fas fa-plus"
                  elevated
                  @click="showTable = !showTable"
                  style="width: 21.4%;"
              >
                견적사 입력
              </VButton>
              <div v-if="showTable" class="mt-2">
                <ComVFlexTable
                    :key="params.prcsBizs.length"
                    :data="params.prcsBizs"
                    :columns="params.prcsBizsColumn"
                    :compact="true"
                    :separators="true"
                    :clickable="true"
                >
                  <template #body-cell="{ row, column, index, value }">
                    <div class="control" :class="column.key === 'actions' ? 'text-center' : ''">
                      <!-- 다른 editable 컬럼은 input -->
                      <input
                          v-if="column.key=='email'"
                          v-model="row[column.key]"
                          class="input custom-text-filter"
                          ref="prcsBizsRef"
                          @blur="onInput(row, column)"
                      />
                      <VIMaskInput
                          v-if="column.key=='bizNo'"
                          v-model="row[column.key]"
                          autocomplete="cc-csc"
                          class="input"
                          :options="{
                                mask: '000-00-0000',
                              }"
                          placeholder="000-00-0000"
                      />
                      <span v-else-if="column.key=='num'">{{index + 1}}</span>
                      <!-- readonly 출력 -->
                      <span v-else-if="column.key=='actions'" class="lnil lnil-close"
                            @click="onDelete(index)">{{ value }}</span>
                    </div>
                  </template>
                </ComVFlexTable>
                <div class="mt-2">
                  <VButton
                      color="primary"
                      icon="fas fa-plus"
                      @click="addNewEstimateRow"
                  >
                    행 추가
                  </VButton>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>규격입력<span style="color: red">*</span></td>
            <td colspan="2">
              <VButton
                  :color="params.btnChangeFlag? 'success':'primary'"
                  icon="fas fa-plus"
                  elevated
                  @click="detailActionsOpen = true"
                  style="width: 100%;"
              >
               <span v-if="!params.btnChangeFlag"> 상세 규격 입력</span>
                <span v-else-if="params.btnChangeFlag"> 상세 규격 등록 완료</span>
              </VButton>
              <VModal
                  :open="detailActionsOpen"
                  actions="center"
                  title="상세 규격 입력"
                  size="contract-big"
                  @close="detailActionsOpen = false"
              >
                <template #content>
                  <div class="form-label">
                  <VButton color="success">일괄업로드</VButton>
                  </div>
                  <ComVFlexTable
                      :key="params.dtlSpecs.length"
                      :data="params.dtlSpecs"
                      :columns="params.dtlSpecsColumn"
                      :separators="true"
                      :clickable="true"
                  >
                    <template #body-cell="{ row, column, index, value }">
                      <!-- 예: 특정 컬럼이면 input, 아니면 그냥 값 출력 -->
                      <div class="control w-100" :class="column.key === 'delete'? 'text-center': ''">
                        <input
                            v-if="column.editable"
                            v-model="row[column.key]"
                            class="input custom-text-filter"
                        />
                        <span v-else-if="column.key=='num'">{{index+1}}</span>
                        <span v-else-if="column.key=='delete'" class="lnil lnil-close"
                              @click="onDetailDelete(index)">{{ value }}</span>
                      </div>
                    </template>
                  </ComVFlexTable>
                  <div class="mt-2">
                    <VButton
                        color="primary"
                        icon="fas fa-plus"
                        @click="addNewDetailRow"
                    >
                      행 추가
                    </VButton>
                  </div>
                </template>
                <template #action>
                  <VButton color="primary" @click="changeButton">
                    등록
                  </VButton>
                </template>
              </VModal>
            </td>
            <td>등록기간<span style="color: red">*</span></td>
            <td colspan="6">
              <div class="columns">
                <div class="column is-4">
                  <VDatePicker
                      v-model="generalParams.regSdat"
                      color="green"
                      trim-weeks
                  >
                    <template #default="{ inputValue, inputEvents }">
                      <VField>
                        <VControl icon="lucide:calendar">
                          <input
                              class="input v-input"
                              type="text"
                              :value="inputValue"
                              v-on="inputEvents"
                              placeholder="시작일"
                          >
                        </VControl>
                      </VField>
                    </template>
                  </VDatePicker>
                </div>
                <div class="column is-1" style="text-align:center; line-height:2rem">
                  <span>~</span>
                </div>
                <div class="column is-4">
                  <VDatePicker
                      v-model="generalParams.regEdat"
                      color="green"
                      trim-weeks
                      disabledDates=""
                  >
                    <template #default="{ inputValue, inputEvents }">
                      <VField>
                        <VControl icon="lucide:calendar">
                          <input
                              class="input v-input"
                              type="text"
                              :value="inputValue"
                              v-on="inputEvents"
                              placeholder="종료일"
                          >
                        </VControl>
                      </VField>
                    </template>
                  </VDatePicker>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>첨부파일</td>
            <td colspan="3">
              <VField>
                <div class="form-label">
                  <div class="file has-name is-fullwidth">
                  <input
                      class="file-input hide"
                      type="file"
                      multiple
                      @change="(e) => onFileChange(e)"
                  >
                  <VLabel>
                    <VButton icon="fas fa-plus" color="info" class="file-trigger" @click="onFileClick" >
                      <span>파일업로드</span>
                    </VButton>
                  </VLabel>
                  </div>
                </div>
                  <VControl>
                    <div
                        v-for="(f, i) in pbAtts"
                        :key="f.logiFnm"
                        class="content estimate-file-wrapper"
                    >
                      <div class="estimate-file-name">
                        {{ f.logiFnm }}{{" ("}}{{Math.ceil(f.size / 1024)}}kb{{")"}}
                      </div>
                      <div>
                        <i class="fa fa-trash estimate-file-delete" @click="onFilDelete(f.bizNo, i, f.fileOrd)" />
                      </div>
                    </div>
                  </VControl>
              </VField>
              <div class="column is-12">
                <VField>
                  <VControl>
                    <div
                        v-for="f in params.prcsAtts"
                        :key="f.logiFnm"
                        class="content estimate-file-wrapper"
                    >
                      <div class="estimate-file-name">
                        {{ f.logiFnm }}{{" ("}}{{Math.ceil(f.size / 1024)}}kb{{")"}}
                      </div>
                      <span>
                        <i class="fa fa-download estimate-file-download" @click="onPrcsFileDownload(f.prcsNo, f.fileOrd, f.logiFnm)" />
                        <i class="fa fa-trash estimate-file-delete" @click="onFilDelete(f.prcsNo, i, f.fileOrd)" />
                      </span>
                    </div>
                  </VControl>
                </VField>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <div class="column is-12">
        <VUserTemp v-model="selectUser"/>
      </div>
      <div class="column is-12">
        <VField class="pr-2">
          <VLabel class="has-fullwidth" style="font-size: 1.3em;">
            결재선
          </VLabel>
        </VField>
        <ComVFlexTable
          :key="apprLine.map(item => item.sabun).join(',')"
          :data="apprLine"
          :columns="params.felxColumn"
          :separators="true"
          :clickable="true"
          :compact="true">
          <template #body-cell="{ row, column, index, value }">
            <!-- 예: 특정 컬럼이면 input, 아니면 그냥 값 출력 -->
            <div class="w-100">
              <span v-if="(index==0 && column.key != 'gubunCd' && column.key != 'attendCd')"  class="column">
                {{value}}
              </span>
              <span v-else-if="(index==0 && column.key == 'gubunCd')" class="column">
                {{"입안"}}
              </span>
              <span v-else-if="(index==0 && column.key == 'attendCd')" class="column">
                {{"재중"}}
              </span>
              <span v-else-if="column.key=='gubunCd'" class="column">
                <VField class="pr-1">
                  <VCodeSelect
                    cd_grp=7
                    v-model="row.gubunCd"/>
                </VField>
              </span>
              <span v-else-if="column.key=='attendCd'" class="column">
                  <VField class="pr-1">
                    <VCodeSelect
                        placeholder="재중"
                        cd_grp=6
                        v-model="row.attendCd">
                    </VCodeSelect>
                  </VField>
                </span>
              <span v-else-if="column.key === 'actions'" class="flex gap-1">
                <VCustomButton v-if="index != 1" @click="moveUp(index)" icon="lucide:arrow-up" />
                <VCustomButton @click="moveDown(index)" icon="lucide:arrow-down" />
                <VCustomButton @click="onPriceDelete(index)">{{"삭제"}}</VCustomButton>
              </span>
              <span v-else>{{value}}</span>
            </div>
          </template>
        </ComVFlexTable>
      </div>
      <div style="display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px;">
      <VButton
          color="primary"
          @click.stop="updatePriceOne()"
          raised>
        수정
      </VButton>
      <VButton
          to="/app/priceManagement"
          v-if="params.stCd === '0000'"
          color="info"
      >
        닫기
      </VButton>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/*css 추가 start*/
.flex-table {
  .flex-table-header {
    padding: 0.1rem !important;
    min-height: 40px;
    border-top-left-radius: .75rem;
    border-top-right-radius: .75rem;
  }

  .flex-table-cell {
    .w-100 {
      width: 100%;
    }
  }
  .flex-table-item {
    padding: 0.1rem !important;
    min-height: 40px;

    .column {
      min-height: 40px;
      padding: 0.1rem !important;
    }

    &:last-child {
      border-bottom-left-radius: .75rem;
      border-bottom-right-radius: .75rem;
    }
  }
}

.table-container {
  overflow:hidden;
  .control {
    width: 100%;
  }
  td {
    padding: 10px 10px !important;
    .columns {
      margin-left: 10px !important;
      padding-top: 10px;
    }
    .column {
      padding: 0 !important;
    }
  }
}

.text-center {
  text-align:center;
}
/*css 추가 end*/
.table tbody td {
  color: var(--smoke-white);
}

.datatable-table  {
  padding: 12px 12px;

  td:nth-child(1) {
    background-color: var(--primary);
  }
  td:nth-child(3) {
    background-color: var(--primary);
  }
}

.iconify {
  font-size: 16px; /* 크기 조절 */
}
</style>