"use client"
import PageBreadcrumb from "@/components/common/PageBreadCrumb2";
import ComponentCard from '@/components/common/ComponentCard2';
import CtTable1 from '@/components/tables/CtTable1';
import Button from '@/components/ui/button/Button2';
import { DocsIcon, TableIcon, PlusIcon, FileIcon, TrashBinIcon, InfoIcon } 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, convertDateTime4, convertDateTime6, useAuthStore } from '@/lib/_AG';
import api2 from '@/lib/_AG';
import CtTree, { CtTreeNode, findNodeByKey } from "@/components/CtTree";
import { reqBizGroupTree2, reqBizGroupTree3 } from "../biz-group/BizGroupContent";
import Checkbox from "@/components/form/input/Checkbox";
import Badge from "@/components/ui/badge/Badge";
import Select from "@/components/form/Select2";


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


export default function UndefinedTransactions() {
  const tokenPayload = useAuthStore((s) => s.tokenPayload);  //Bruce, JWT
  
  const [ tableData, setTableData ] = useState<any[]>([]);
  const [ tableOffset, setTableOffset ] = useState<number>(0);
  const [ tableTotalCount, setTableTotalCount ] = useState<number>(0);

  //search fields
  const [ uid1, setUid1 ] = useState<string>("");
  const [ amount, setAmount ] = useState<string>("");
  const [ type, setType ] = useState<string>("");
  const [ approval, setApproval ] = useState<string>("");
  const [ slot, setSlot ] = useState<string>("");
  const [ code, setCode ] = useState<string>("");
  const [ goods_name, setGoodsName ] = useState<string>("");
  const [ pay_vendor, setPayVendor ] = useState<string>("");
  const [ date_start, setDateStart ] = useState<string>("");
  const [ date_end, setDateEnd ] = useState<string>("");


  //function part
  //
  function reqTransactionList() {
    const params = {
      offset: tableOffset,
      limit: COUNT_PER_PAGE,
      uid1: uid1,
      amount: amount,
      type: type,
      approval: approval,
      slot: slot,
      code: code,
      goods_name: goods_name,
      pay_vendor: pay_vendor,
      date_start: date_start,
      date_end: date_end,
    }

    api.post('/api/get-u-transaction.do', params).then((resp) => {
      console.log(resp);

      if (resp.data.errCode === 0) {
        if (resp.data.result.list.length == 0) {
          alert("조회 결과가 없습니다.");
          setTableTotalCount(0);
          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
  //
  const handleClickSearch = () => {
    reqTransactionList();
  };

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

  const handleRowClickDelete = (row: number) => {
    if (tableData[row].type != "D1" && tableData[row].type != "I1" &&  
      tableData[row].type != "TM1" && tableData[row].type != "EB1") {
        alert("이미 취소 처리된 항목입니다.");
        return;
      }

    if (confirm("'" + tableData[row].approval + "'을 승인취소 요청하시겠습니까?")) {

      let s01;
      if (tableData[row].type === "D1")
        s01 = "D4";
      else if (tableData[row].type === "I1")
        s01 = "I4";
      else if (tableData[row].type === "TM1")
        s01 = "T2";
      else if (tableData[row].type === "EB1")
        s01 = "T2";

      const params = "S01=" + s01 + ";S02=40;S07=" + tableData[row].pay_unique_num + ";S10=" + tableData[row].amount + ";S12=" + tableData[row].approval + ";S13=" +  + tableData[row].order_time.substring(0, 6) + ";";
      //const params = "S01=D4;S02=40;S07=" + tableData[row].pay_unique_num + ";S10=" + tableData[row].amount + ";S12=" + tableData[row].approval + ";S13=260106;";
      //api2.post("/tapi/cancel.do", params);

      console.log("---params: ", params);

      const res = fetch("/tapi/cancel.do?tid=" + tableData[row].uid1, {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain; charset=UTF-8',
        },
        body: params,
      });
    }    
  };
  //

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

    reqTransactionList();
  }, [tokenPayload]);

  useEffect(() => {
    reqTransactionList();
  }, [tableOffset]);


  const columns = [
    /*
    {
      title: "서버 수신시간",
      key: "reg_time",
      renderItem: (item: any, row: number) => convertDateTime3(item.reg_time)
    },
    */
    {
      title: "거래시간",
      key: "order_time",
      renderItem: (item: any, row: number) => convertDateTime6(item.order_time)
    },
    /*
    {
      title: "무인기기명",
      key: "device_name",
    },
    */
    {
      title: "단말기 TID",
      key: "uid1",
    },
    {
      title: "금액",
      key: "amount",
      renderItem: (item : any) => (item.amount.toLocaleString("ko-KR") + "원")
    },
    {
      title: "결제유형",
      key: "type",
      renderItem: (item : any) => (
        <Badge size="sm" color={
          item.type === "D1" ? "primary" : 
          item.type === "I1" ? "info" : 
          item.type === "B1" ? "warning" :
          item.type === "TM1" ? "light" :
          item.type === "EB1" ? "success" :
          "error"
          }>
          {item.type === "D1" ? "신용승인" : 
            item.type === "D4" ? "신용취소" :
            item.type === "I1" ? "페이승인" :
            item.type === "I4" ? "페이취소" :
            item.type === "B1" ? "현금" :
            item.type === "TM1" ? "티머니승인" :
            item.type === "TM4" ? "티머니취소" :
            item.type === "EB1" ? "캐시비승인" :
            item.type === "EB4" ? "캐시비취소" : 
            ""}
        </Badge> 
      )
    },
    {
      title: "승인번호",
      key: "approval",
    },
    {
      title: "컬럼번호",
      key: "slot",
    },
    {
      title: "상품코드",
      key: "code",
    },
    {
      title: "상품명",
      key: "goods_name",
    },
    {
      title: "결제서비스업체",
      key: "pay_vendor",
      renderItem: (item : any) => (
        item.type === "TM1" ? "티머니" :
        item.type === "TM4" ? "티머니" :
        item.type === "EB1" ? "캐시비" :
        item.type === "EB4" ? "캐시비" : 
        item.pay_vendor
      )
    },
    {
      title: "취소요청",
      key: "_",
      renderItem: (item: any, row: number) => (
        item.type == "D1" ? 
        <div>
          <InfoIcon 
            className="cursor-pointer hover:fill-error-500 dark:hover:fill-error-500 fill-gray-700 dark:fill-gray-400"
            onClick={() => {handleRowClickDelete(row)}} />
        </div>
        : ""
      ),
    },
  ];

  return (
    <div>
      <PageBreadcrumb pageTitle1="매출 및 통계" pageTitle2="거래내역 조회" />

      <div className="space-y-3">

        <ComponentCard title="거래내역 목록" titleIcon={<TableIcon />}>
          <div className="space-y-3">
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
              <WithLabel label="단말기 TID" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="단말기 TID를 입력하세요." value={uid1} onChange={(e) => setUid1(e.target.value)} />
              </WithLabel>						
              <WithLabel label="금액" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="금액을 입력하세요." value={amount} onChange={(e) => setAmount(e.target.value)} />
              </WithLabel>
              <WithLabel label="결제유형" label_width={SEARCH_LABEL_WIDTH}>
                <Select
                  placeholder="선택하세요"
                  options={[
                      { label: "신용승인", value: "D1" },
                      { label: "신용취소", value: "D4" },
                      { label: "페이승인", value: "I1" },
                      { label: "페이취소", value: "I4" },
                      { label: "현금", value: "B1" },
                      { label: "티머니승인", value: "TM1" },
                      { label: "캐니비승인", value: "EB1" },
                  ]}
                  defaultValue={type} onChange={(value) => setType(value)}
                  className="dark:bg-dark-900" />
              </WithLabel>
              <WithLabel label="승인번호" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="승인번호를 입력하세요." value={approval} onChange={(e) => setApproval(e.target.value)} />
              </WithLabel>
            </div>
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
              <WithLabel label="컬럼번호" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="컬럼번호를 입력하세요." value={slot} onChange={(e) => setSlot(e.target.value)} />
              </WithLabel>
              <WithLabel label="상품코드" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="상품코드를 입력하세요." value={code} onChange={(e) => setCode(e.target.value)} />
              </WithLabel>
              <WithLabel label="상품명" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="상품명을 입력하세요." value={goods_name} onChange={(e) => setGoodsName(e.target.value)} />
              </WithLabel>
              <WithLabel label="결제업체" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="결제업체를 입력하세요." value={pay_vendor} onChange={(e) => setPayVendor(e.target.value)} />
              </WithLabel>
            </div>
            <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></div>
              <div className="flex items-center justify-end gap-5">
                <Button size="sm" variant="outline" startIcon={<DocsIcon />}>엑셀파일 다운로드</Button>
                <Button size="sm" variant="primary" onClick={handleClickSearch}>조회</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>
  );
}
