'use client'

import React, { useEffect, useState, useRef } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { Button } from '@nextui-org/react'
import { useAxios } from '@/hooks/useAxios'
import { useMessage } from '@/hooks/useMessage'
import StuffQGrid from './StuffQGrid'
import { useRecoilValue, useRecoilState } from 'recoil'
import { stuffSearchState } from '@/store/stuffAtom'
import { queryStringFormatter, isEmptyArray } from '@/util/common-utils'
import dayjs from 'dayjs'
import { isObjectNotEmpty } from '@/util/common-utils'
import { convertNumberToPriceDecimal } from '@/util/common-utils'
import { appMessageStore, globalLocaleStore } from '@/store/localeAtom'
import KO from '@/locales/ko.json'
import JA from '@/locales/ja.json'
import QPagination from '../common/pagination/QPagination'
import { sessionStore } from '@/store/commonAtom'

export default function Stuff() {
  const sessionState = useRecoilValue(sessionStore)
  const [appMessageState, setAppMessageState] = useRecoilState(appMessageStore)
  const stuffSearchParams = useRecoilValue(stuffSearchState)
  const [stuffSearch, setStuffSearch] = useRecoilState(stuffSearchState)
  const { getMessage } = useMessage()
  const [pageNo, setPageNo] = useState(1) //현재 페이지 번호
  const [pageSize, setPageSize] = useState(100) //페이지 당 게시물 수
  const [totalCount, setTotalCount] = useState(0) //총 갯수
  const [defaultSortType, setDefaultSortType] = useState('R')

  const globalLocaleState = useRecoilValue(globalLocaleStore)
  const { get } = useAxios(globalLocaleState)
  const gridRef = useRef()

  const [selectedRowData, setSelectedRowData] = useState([])
  const [selectedRowDataCount, setSelectedRowDataCount] = useState(0)

  const router = useRouter()
  const pathname = usePathname()

  //그리드 내부 복사버튼
  const copyNo = async (value) => {
    try {
      await navigator.clipboard.writeText(value)
      alert('물건번호가 복사되었습니다.')
    } catch (error) {
      alert('물건번호 복사에 실패했습니다.')
    }
  }

  //물건번호 복사버튼 옆에 영역
  const onDoubleClick = (e) => {
    let objectNo = e.target.innerText
    if (objectNo.substring(0, 1) === 'R') {
      router.push(`${pathname}/detail?objectNo=${objectNo.toString()}`, { scroll: false })
    } else {
      router.push(`${pathname}/tempdetail?objectNo=${objectNo.toString()}`, { scroll: false })
    }
  }

  const [gridProps, setGridProps] = useState({
    gridData: [],
    isPageable: false,
    gridColumns: [
      {
        field: 'lastEditDatetime',
        minWidth: 200,
        headerName: getMessage('stuff.gridHeader.lastEditDatetime'),
        headerCheckboxSelection: true,
        headerCheckboxSelectionCurrentPageOnly: true, //페이징시 현재 페이지만 체크되도록
        checkboxSelection: true,
        showDisabledCheckboxes: true,
        cellStyle: { textAlign: 'center' },
        valueFormatter: function (params) {
          if (params.value) {
            return dayjs(params?.value).format('YYYY.MM.DD HH:mm:ss')
          } else {
            return null
          }
        },
      },
      {
        field: 'objectNo',
        minWidth: 230,
        headerName: getMessage('stuff.gridHeader.objectNo'),
        cellRenderer: function (params) {
          if (params.data.objectNo) {
            return (
              <div>
                <Button
                  size="sm"
                  color="default"
                  onPress={() => {
                    copyNo(params.value)
                  }}
                >
                  복사
                </Button>
                <span onDoubleClick={onDoubleClick}>{params.value}</span>
              </div>
            )
          }
        },
        cellRendererParams: {
          onPress: copyNo,
        },
      },
      {
        field: 'planTotCnt',
        headerName: getMessage('stuff.gridHeader.planTotCnt'),
        cellStyle: { textAlign: 'right' },
      },
      { field: 'objectName', headerName: getMessage('stuff.gridHeader.objectName'), cellStyle: { textAlign: 'left' } },
      {
        field: 'saleStoreId',
        headerName: getMessage('stuff.gridHeader.saleStoreId'),
        cellStyle: { textAlign: 'left' },
      },
      { field: 'saleStoreName', minWidth: 300, headerName: getMessage('stuff.gridHeader.saleStoreName'), cellStyle: { textAlign: 'left' } },
      { field: 'address', headerName: getMessage('stuff.gridHeader.address'), cellStyle: { textAlign: 'left' } },
      { field: 'dispCompanyName', headerName: getMessage('stuff.gridHeader.dispCompanyName'), cellStyle: { textAlign: 'left' } },
      { field: 'receiveUser', headerName: getMessage('stuff.gridHeader.receiveUser'), cellStyle: { textAlign: 'left' } },
      {
        field: 'specificationConfirmDate',
        headerName: getMessage('stuff.gridHeader.specificationConfirmDate'),
        valueFormatter: function (params) {
          if (params.value) {
            return dayjs(params?.value).format('YYYY.MM.DD')
          } else {
            return null
          }
        },
        cellStyle: { textAlign: 'center' },
      },
      {
        field: 'createDatetime',
        headerName: getMessage('stuff.gridHeader.createDatetime'),
        valueFormatter: function (params) {
          if (params.value) {
            return dayjs(params?.value).format('YYYY.MM.DD')
          } else {
            return null
          }
        },
        cellStyle: { textAlign: 'center' },
      },
    ],
    gridCount: 0,
  })

  //그리드 더블클릭
  const getCellDoubleClicked = (event) => {
    if (event.column.colId === 'objectNo') {
      return
    } else {
      //T 면 임시 R은 진짜
      if (event.data.objectNo) {
        if (event.data.objectNo.substring(0, 1) === 'R') {
          router.push(`${pathname}/detail?objectNo=${event.data.objectNo.toString()}`, { scroll: false })
        } else {
          router.push(`${pathname}/tempdetail?objectNo=${event.data.objectNo.toString()}`, { scroll: false })
        }
      }
    }
  }

  //그리드 체크박스 선택시
  const getSelectedRowdata = (data) => {
    setSelectedRowData(data)
    setSelectedRowDataCount(data.length)
  }

  //물건삭제
  const fnDeleteRowData = (data) => {
    console.log('물건삭제:::::::::::')
    if (data.length === 0) {
      return alert('삭제할 데이터를 선택하세요')
    }
    let errCount = 0
    data.forEach((cell) => {
      if (!cell.objectNo) {
        if (errCount === 0) {
          alert('물건정보가 있는 행만 삭제 됩니다')
        }
        errCount++
      }
    })
  }

  //행추가
  let newCount = 0
  const addRowItems = () => {
    // console.log('girdRef::::::', gridRef.current.api)
    const newItems = [
      {
        mission: newCount + 1,
        successful: true,
      },
    ]
    gridRef.current.api.applyTransaction({
      add: newItems,
      addIndex: newCount,
    })
    newCount++
  }

  //행삭제
  const removeRowItems = () => {
    // console.log('selectedRowData::', selectedRowData)
    let errCount = 0
    selectedRowData.forEach((cell) => {
      if (!cell.company) {
        let newSelectedRowData = selectedRowData.filter((item) => item.company == null)
        gridRef.current.api.applyTransaction({ remove: newSelectedRowData })
      } else {
        if (errCount === 0) {
          alert('행추가로 추가 한 행만 삭제됩니다.')
        }
        errCount++
      }
    })
  }

  // 진입시 그리드 데이터 조회
  useEffect(() => {
    if (isObjectNotEmpty(sessionState)) {
      //물건 메뉴 눌러서 최초 진입 sessionState
      if (stuffSearchParams?.code === 'S') {
        const params = {
          saleStoreId: sessionState?.storeId,
          schObjectNo: stuffSearchParams?.schObjectNo,
          schAddress: stuffSearchParams?.schAddress,
          schObjectName: stuffSearchParams?.schObjectName,
          schSaleStoreName: stuffSearchParams?.schSaleStoreName,
          schReceiveUser: stuffSearchParams?.schReceiveUser,
          schDispCompanyName: stuffSearchParams?.schDispCompanyName,
          schDateType: stuffSearchParams.schDateType,
          schFromDt: dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'),
          schToDt: dayjs(new Date()).format('YYYY-MM-DD'),
          startRow: (pageNo - 1) * pageSize + 1,
          endRow: pageNo * pageSize,
          schSelSaleStoreId: '',
          schSortType: stuffSearchParams.schSortType,
        }

        async function fetchData() {
          const apiUrl = `/api/object/list?${queryStringFormatter(params)}`
          await get({
            url: apiUrl,
          }).then((res) => {
            if (!isEmptyArray(res)) {
              setGridProps({ ...gridProps, gridData: res, count: res[0].totCnt })
              setTotalCount(res[0].totCnt)
            }
          })
        }
        fetchData()
      } else {
        //메인화면에서 진입
        const params = {
          saleStoreId: sessionState?.storeId,
          schObjectNo: stuffSearchParams.schObjectNo,
          schAddress: '',
          schObjectName: '',
          schSaleStoreName: '',
          schReceiveUser: '',
          schDispCompanyName: '',
          schDateType: 'U',
          schFromDt: dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'),
          schToDt: dayjs(new Date()).format('YYYY-MM-DD'),
          startRow: (pageNo - 1) * pageSize + 1,
          endRow: pageNo * pageSize,
          schSelSaleStoreId: '',
          schSortType: 'R',
        }

        async function fetchData() {
          const apiUrl = `/api/object/list?${queryStringFormatter(params)}`
          await get({
            url: apiUrl,
          }).then((res) => {
            if (!isEmptyArray(res)) {
              setGridProps({ ...gridProps, gridData: res, count: res[0].totCnt })
              setTotalCount(res[0].totCnt)
            }
          })
        }
        fetchData()
      }
    }
  }, [pageNo, sessionState])

  useEffect(() => {
    if (stuffSearchParams?.code === 'E') {
      stuffSearchParams.startRow = 1
      stuffSearchParams.endRow = 1 * pageSize
      stuffSearchParams.schSortType = defaultSortType

      setPageNo(1)
      //조회를 눌렀을때
      async function fetchData() {
        const apiUrl = `/api/object/list?saleStoreId=${sessionState?.storeId}&${queryStringFormatter(stuffSearchParams)}`
        await get({ url: apiUrl }).then((res) => {
          if (!isEmptyArray(res)) {
            setGridProps({ ...gridProps, gridData: res, count: res[0].totCnt })
            setTotalCount(res[0].totCnt)
          } else {
            setGridProps({ ...gridProps, gridData: [], count: 0 })
            setTotalCount(0)
          }
        })
      }
      fetchData()
    }
  }, [stuffSearchParams])

  //페이지 갯수 변경 이벤트
  const onChangePerPage = (e) => {
    let startRow = (1 - 1) * e.target.value + 1
    stuffSearchParams.startRow = startRow
    stuffSearchParams.endRow = 1 * e.target.value
    setPageSize(e.target.value)
    setStuffSearch({
      ...stuffSearch,
      code: 'S',
      startRow: startRow,
      endRow: 1 * e.target.value,
    })

    setPageNo(1)
    const apiUrl = `/api/object/list?saleStoreId=${sessionState?.storeId}&${queryStringFormatter(stuffSearchParams)}`
    get({ url: apiUrl }).then((res) => {
      if (!isEmptyArray(res)) {
        setGridProps({ ...gridProps, gridData: res, count: res[0].totCnt })
        setTotalCount(res[0].totCnt)
      } else {
        setGridProps({ ...gridProps, gridData: [], count: 0 })
        setTotalCount(0)
      }
    })
  }

  //최근 등록일 수정일 정렬 이벤트
  const onChangeSortType = (e) => {
    let startRow = (1 - 1) * pageSize + 1
    stuffSearchParams.startRow = startRow
    stuffSearchParams.endRow = 1 * pageSize

    stuffSearchParams.schSortType = e.target.value
    setDefaultSortType(e.target.value)
    setStuffSearch({
      ...stuffSearch,
      code: 'S',
      startRow: startRow,
      endRow: 1 * pageSize,
      schSortType: e.target.value,
    })

    setPageNo(1)

    const apiUrl = `/api/object/list?saleStoreId=${sessionState?.storeId}&${queryStringFormatter(stuffSearchParams)}`
    get({ url: apiUrl }).then((res) => {
      if (!isEmptyArray(res)) {
        setGridProps({ ...gridProps, gridData: res, count: res[0].totCnt })
        setTotalCount(res[0].totCnt)
      } else {
        setGridProps({ ...gridProps, gridData: [], count: 0 })
        setTotalCount(0)
      }
    })
  }

  useEffect(() => {
    if (globalLocaleState === 'ko') {
      setAppMessageState(KO)
    } else {
      setAppMessageState(JA)
    }
  }, [globalLocaleState])

  // 페이징 현재페이지 변경
  const handleChangePage = (page) => {
    stuffSearchParams.code = 'S'

    setStuffSearch({
      ...stuffSearch,
      code: 'S',
      startRow: (page - 1) * pageSize + 1,
      endRow: page * pageSize,
    })

    setPageNo(page)
  }

  return (
    <>
      {/* 퍼블시작 */}
      <div className="sub-table-box">
        <div className="table-box-title-wrap">
          <div className="title-wrap">
            <h3>{getMessage('stuff.search.grid.title')}</h3>
            <ul className="info-wrap">
              <li>
                {getMessage('stuff.search.grid.all')}
                <span>{convertNumberToPriceDecimal(totalCount)}</span>
              </li>
              <li>
                {getMessage('stuff.search.grid.selected')}
                <span className="red">{convertNumberToPriceDecimal(selectedRowDataCount)}</span>
              </li>
            </ul>
          </div>
          <div className="left-unit-box">
            <div className="select-box mr5" style={{ width: '110px' }}>
              <select className="select-light black" name="" id="" onChange={onChangeSortType}>
                <option value="R">{getMessage('stuff.search.grid.schSortTypeR')}</option>
                <option value="U">{getMessage('stuff.search.grid.schSortTypeU')}</option>
              </select>
            </div>
            <div className="select-box" style={{ width: '80px' }}>
              <select className="select-light black" name="" id="" onChange={onChangePerPage}>
                <option value="100">100</option>
                <option value="200">200</option>
                <option value="300">300</option>
              </select>
            </div>
          </div>
        </div>
        <div className="grid-table-wrap">
          <div className="q-grid">
            <StuffQGrid {...gridProps} getSelectedRowdata={getSelectedRowdata} getCellDoubleClicked={getCellDoubleClicked} gridRef={gridRef} />
            <div className="pagination-wrap">
              <QPagination pageNo={pageNo} pageSize={pageSize} pagePerBlock={10} totalCount={totalCount} handleChangePage={handleChangePage} />
            </div>
          </div>
        </div>
      </div>
      {/* 퍼블종료 */}
    </>
  )
}
