"use client"
import PageBreadcrumb from "@/components/common/PageBreadCrumb2";
import ComponentCard from '@/components/common/ComponentCard2';
import BizGroupPanel from "@/components/common/BizGroupPanel";
import CtTable1 from '@/components/tables/CtTable1';
import Button from '@/components/ui/button/Button2';
import { DocsIcon, PlusIcon, TableIcon, ChevronDownIcon } from "@/icons";
import WithLabel from '@/components/form/WithLabel';
import Input from '@/components/form/input/InputField2';
import DatePicker from '@/components/form/date-picker2';

import React, { Key } from "react";
import { useEffect, useState } from 'react';
import api, { convertDateTime3, postFileDownload, useAuthStore, useUiLoadingStore } from '@/lib/_AG';
import CtTree, { CtTreeNode, findNodeByKey, findRootNodeByKey, getAllNodeKeys } from "@/components/CtTree";
import { reqBizGroupTree2, reqBizGroupTree3 } from "../biz-group/BizGroupContent";
import Checkbox from "@/components/form/input/Checkbox";
import Select from "@/components/form/Select2";


const SEARCH_LABEL_WIDTH = 24;
const COUNT_PER_PAGE = 10;
const PAGE_NUM_COUNT = 5;


export default function Sales() {
  const tokenPayload = useAuthStore((s) => s.tokenPayload);  //Bruce, JWT
  const isLoadingGlobal = useUiLoadingStore((s) => s.isLoading);

  const [ tableData, setTableData ] = useState<any[]>([]);
  const [ tableOffset, setTableOffset ] = useState<number>(0);
  const [ tableTotalCount, setTableTotalCount ] = useState<number>(0);

  const [ treeData, setTreeData ] = useState<CtTreeNode[]>([]);
  const [ selectedTreeKeys, setSelectedTreeKeys ] = useState<Key[]>([]);
  const [ expandedTreeKeys, setExpandedTreeKeys ] = useState<Key[]>([]);
  const [ isGroupAccess, setGroupAccess ] = useState(tokenPayload?.permission == 1);  //TempCode
  const [ isTreeOpen, setTreeOpen ] = useState(tokenPayload?.permission == 1);  //TempCode  

  // group search fields
  const [ name, setName ] = useState<string>("");
  const [ biz_reg_num, setBizRegNum ] = useState<string>("");

  //search fields
  const [ device_name, setDeivceName ] = useState<string>("");
  const [ uid1, setUid1 ] = useState<string>("");
  const [ approval_type, setApprovalType ] = useState<string>("0");
  const [ date_type, setDateType ] = useState<string>("1");
  const [ date_start, setDateStart ] = useState<string>("");
  const [ date_end, setDateEnd ] = useState<string>("");

  // function part
  //
  function reqSalesList(is_excel: boolean, biz_group_id: string, groupAccess: boolean) {
    if (!biz_group_id)
      return;

    const params = {
      is_group_access: groupAccess,
      is_excel: is_excel,
      offset: tableOffset,
      limit: COUNT_PER_PAGE,
      biz_group_id: biz_group_id,
      device_name: device_name,
      uid1: uid1,
      approval_type: approval_type,
      date_type: date_type,
      date_start: date_start,
      date_end: date_end,
    }

    if (is_excel == true) {
      postFileDownload('/api/get-sales.do', params);
      return;
    }

    api.post('/api/get-sales.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          if (resp.data.result.list.length == 0) {
              alert("조회 결과가 없습니다.");
              setTableData([]);
              return;
          }

          setTableTotalCount(resp.data.result.totalCount);
          setTableData(resp.data.result.list);
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }


  // event processing part
  //
  // tree part //////////
 const handleClickGroupSearch = () => {
    if (tokenPayload?.permission == 1) {
      if (name == "" && biz_reg_num == "") {
        alert("그룹명(사업자명) 또는 사업자등록번호를 입력하셔야 합니다.");
        return;
      }
      if (name != "" && name.length < 3) {
        alert("그룹명(사업자명)은 세글자 이상 입력해야 합니다.");
        return;
      }
      if (biz_reg_num != "" && biz_reg_num.length < 3) {
        alert("사업자등록번호는 세글자 이상 입력해야 합니다.");
        return;
      }

      reqBizGroupTree2(true, "", "", "", "", name, biz_reg_num, treeData, setTreeData);
    }
    else {
      reqBizGroupTree3(String(tokenPayload?.biz_group_id), setTreeData, setSelectedTreeKeys, setExpandedTreeKeys, (resp: any) => {
        //reqSalesList(false, String(tokenPayload?.biz_group_id), tokenPayload?.permission == 1);
        reqSalesList(false, String(tokenPayload?.biz_group_id), isGroupAccess);
      });
    }
  };

  const handleClickNode = (key: Key) => {
    if (isGroupAccess == false) {
      const root = findRootNodeByKey(treeData, key as string);
      reqSalesList(false, root.key as string, isGroupAccess);
      return;
    }

    setTableOffset(0);
    reqSalesList(false, key as string, isGroupAccess);
  }

  const handleClickTreeExpanded = (key: Key) => {
    const node = findNodeByKey(treeData, key);
    if (node.children == undefined)
      reqBizGroupTree2(false, key as string, "", "", "", "", "2", treeData, setTreeData);
  }

  const handleClickGroupAccess = (value: boolean) => {
    setGroupAccess(value);
    
    if (tokenPayload?.permission == 1) {
      if (selectedTreeKeys.length <= 0) {
        return;
      }

      reqSalesList(false, selectedTreeKeys[0] as string, value);
      return;
    }

    if (value == false || selectedTreeKeys.length <= 0) {
      reqSalesList(false, String(tokenPayload?.biz_group_id), value);
    }
    else {
      console.log("selectedTreeKeys[0] = ", selectedTreeKeys[0]);
      reqSalesList(false, selectedTreeKeys[0] as string, value);
    }
  }
  // tree part //////////

  const handleClickDownload = () => {
    reqSalesList(true, selectedTreeKeys[0] as string, isGroupAccess);
  };

  const handleClickSearch = () => {
    if (selectedTreeKeys.length <= 0) {
      alert("조회하려면 사업자를 선택해야 합니다.");
      return;
    }
    
    reqSalesList(false, selectedTreeKeys[0] as string, isGroupAccess);
  };

  const handlePageChange = (page: number) => {
    setTableOffset((page - 1) * COUNT_PER_PAGE);
  };
  //


  useEffect(() => {
    if (tokenPayload == undefined)
      return;

    if (tokenPayload?.permission == 1)
      return;

    reqBizGroupTree3(String(tokenPayload?.biz_group_id), setTreeData, setSelectedTreeKeys, setExpandedTreeKeys, (resp: any) => {
      setGroupAccess(tokenPayload?.permission == 1);
      setTreeOpen(tokenPayload?.permission == 1);

      reqSalesList(false, String(resp.data.result.tree[0].key), tokenPayload?.permission == 1);
    });
  }, [tokenPayload]);

  useEffect(() => {
    reqSalesList(false, selectedTreeKeys[0] as string, isGroupAccess);
  }, [tableOffset]);


  const columns = [
    {
      title: "날짜",
      key: "date",
    },
    /*
    {
      title: "그룹",
      key: "biz_group_name",
    },
    */
    {
      title: "무인기기명",
      key: "device_name",
    },
    {
      title: "단말기TID",
      key: "uid1",
    },
    {
      title: "카드건수",
      key: "card_count",
    },
    {
      title: "카드금액",
      key: "card_amount",
      renderItem: (item : any) => (item.card_amount.toLocaleString("ko-KR") + "원")
    },
    {
      title: "현금건수",
      key: "cash_count",
    },
    {
      title: "현금금액",
      key: "cash_amount",
      renderItem: (item : any) => (item.cash_amount.toLocaleString("ko-KR") + "원")
    },{
      title: "T머니건수",
      key: "tmoney_count",
    },
    {
      title: "T머니금액",
      key: "tmoney_amount",
      renderItem: (item : any) => (item.tmoney_amount.toLocaleString("ko-KR") + "원")
    },{
      title: "캐시비건수",
      key: "cbee_count",
    },
    {
      title: "캐시비금액",
      key: "cbee_amount",
      renderItem: (item : any) => (item.cbee_amount.toLocaleString("ko-KR") + "원")
    },
    {
      title: "합계",
      key: "total",
      renderItem: (item : any) => (item.total.toLocaleString("ko-KR") + "원")
    }
  ];

  return (
    <div>
      <PageBreadcrumb pageTitle1="매출 및 통계" pageTitle2="매출집계" />

      <div className="space-y-3">
        <BizGroupPanel
          title="사업자 그룹별로 관리"
          isOpen={isTreeOpen}
          setOpen={setTreeOpen}
          name={name}
          bizRegNum={biz_reg_num}
          onChangeName={setName}
          onChangeBizRegNum={setBizRegNum}
          onClickSearch={handleClickGroupSearch}
          isDisabled={isLoadingGlobal}
          searchLabelWidth={SEARCH_LABEL_WIDTH}
        >
          <CtTree
            treeData={treeData}
            selectedKeys={selectedTreeKeys}
            setSelectedKeys={setSelectedTreeKeys}
            onClickNode={handleClickNode}
            expandedKeys={expandedTreeKeys}
            setExpandedKeys={setExpandedTreeKeys}
            onClickExpanded={handleClickTreeExpanded}
          />
        </BizGroupPanel>
        
        <ComponentCard title="매출 집계" titleIcon={<TableIcon />}>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
            <WithLabel label="일별/월별" label_width={SEARCH_LABEL_WIDTH}>
              <Select
                placeholder="선택하세요"
                options={[
                    { label: "일별집계", value: "1" },
                    { label: "월별집계", value: "2" },
                ]}
                defaultValue={date_type} onChange={(value) => setDateType(value)}
                className="dark:bg-dark-900" />
            </WithLabel>
            <WithLabel label="승인/취소" label_width={SEARCH_LABEL_WIDTH}>
              <Select
                placeholder="선택하세요"
                options={[
                    { label: "전체", value: "0" },
                    { label: "승인", value: "1" },
                    { label: "취소", value: "2" },
                ]}
                defaultValue={approval_type} onChange={(value) => setApprovalType(value)}
                className="dark:bg-dark-900" />
            </WithLabel>
            <WithLabel label="무인기기명" label_width={SEARCH_LABEL_WIDTH}>
              <Input type="text" placeholder="승인번호를 입력하세요." value={device_name} onChange={(e) => setDeivceName(e.target.value)} />
            </WithLabel>
            <WithLabel label="단말기 TID" label_width={SEARCH_LABEL_WIDTH}>
              <Input type="text" placeholder="금액을 입력하세요." value={uid1} onChange={(e) => setUid1(e.target.value)} />
            </WithLabel>
          </div>
          <div className="space-y-3">
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
              <WithLabel label="등록일" label_width={SEARCH_LABEL_WIDTH}>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                  <DatePicker
                    id="date_start-picker"
                    placeholder="조회 시작일"
                    onChange={(dates, currentDateString) => { setDateStart(currentDateString); }}
                  />
                  <DatePicker
                    id="date_end-picker"
                    placeholder="조회 종료일"
                    onChange={(dates, currentDateString) => { setDateEnd(currentDateString); }}
                  />
                </div>
              </WithLabel>
              <div className="flex items-center gap-3">
                { isTreeOpen && <>
                <Checkbox checked={isGroupAccess} onChange={(value) => handleClickGroupAccess(value)} />
                <span className="block font-normal text-gray-700 text-theme-sm dark:text-gray-400">
                  그룹단위로 조회
                </span>
                </>}
              </div>
              <div className="flex items-center justify-end gap-5">
                <Button size="sm" variant="outline" startIcon={<DocsIcon />} onClick={handleClickDownload}>엑셀파일 다운로드</Button>
                <Button size="sm" variant="primary" onClick={handleClickSearch} disabled={isLoadingGlobal}>조회</Button>
              </div>
            </div>
          </div>

          <CtTable1 columns={columns} bodyData={tableData} 
            offset={tableOffset} totalCount={tableTotalCount} countPerPage={COUNT_PER_PAGE} pageNumCount={PAGE_NUM_COUNT}
            onClickPageChange={handlePageChange} />

        </ComponentCard>

      </div>
    </div>
  );
}
