"use client";

import { DeleteOutlined, EditOutlined, PlusOutlined, ExclamationCircleOutlined, SyncOutlined } from '@ant-design/icons';
import { Button, Divider, message, Drawer, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
// import CreateUserForm from './components/CreateUserForm';
// import UpdateUserForm from './components/UpdateUserForm';
// import type { UserInfo, UserListItem } from './data.d';
// import {
//   queryUserList,
//   updateUser,
//   addUser,
//   removeUser,
// } from './service';
import md5 from 'md5';
import {
  PaymentInfo,
  UserInfo, queryBillingList, queryDocsList,
  removeDocs,
  syncDocs
} from '@/lib/http/staff';
import Link from 'next/link';

const { confirm } = Modal;

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: UserInfo) => {
  const hide = message.loading('正在添加');
  try {
    fields.password = md5(fields.password)
    fields.user_alias = fields.user_name
    console.log("----------:", fields)

    // await addUser({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: UserInfo) => {
  const hide = message.loading('正在更新');
  try {
    // fields.deptId = Number(fields.deptId)
    fields.password = md5(fields.password)
    // await updateUser(fields);
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (staffId: number, selectedRows: PaymentInfo[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;


  console.log("------>", selectedRows)
  try {
    await removeDocs({
      staff_id: staffId,
      ids: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


/**
 *  同步文档节点
 * @param selectedRows
 */
const handleSync = async (staffId: number) => {
  const hide = message.loading('正在同步');

  console.log("--handleSync---->", staffId)
  try {
    await syncDocs({
      staff_id: staffId,
    });
    hide();
    message.success('同步成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('同步失败，请重试');
    return false;
  }
};

const BillingList: React.FC<{ staffId?: string, serial_no?: string }> = ({ staffId, serial_no }) => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<PaymentInfo>();
  const [selectedRowsState, setSelectedRows] = useState<PaymentInfo[]>([]);

  const showDeleteConfirm = (item: PaymentInfo) => {
    confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined />,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        handleRemove(Number(staffId), [item]).then(() => {
          actionRef.current?.reloadAndRest?.();
        });
      },
      onCancel() {
      },
    });
  };



  const columns: ProColumns<PaymentInfo>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '客户ID',
      dataIndex: 'customer_id',
      hideInSearch: true,
      // render: (dom, entity) => {
      //   return <a onClick={() => {
      //     setCurrentRow(entity);
      //     setShowDetail(true);
      //   }}>{dom}</a>;
      // },
    },
    {
      title: '员工ID',
      dataIndex: 'staff_id',
      hideInSearch: true,
    },

    {
      title: '支付方式',
      dataIndex: 'pay_type',
      valueEnum: {
        'wxpay': { text: '微信', status: 'wxpay' },
        'alipay': { text: '支付宝', status: 'alipay' },
        'stripe': { text: 'Stripe支付', status: 'stripe' },
      },
      hideInSearch: true,
    },
    // {
    //   title: '商家交易订单号',
    //   dataIndex: 'trade_no',
    //   hideInSearch: true,
    //   // hideInTable: true,
    // },
    // {
    //   title: '支付平台唯一交易ID',
    //   dataIndex: 'transaction_id',
    //   hideInSearch: true,
    // },
    {
      title: '产品ID',
      dataIndex: 'prod_id',
      hideInSearch: true,
    },
    {
      title: '产品名称',
      dataIndex: 'prod_name',
      hideInSearch: true,
    },
    {
      title: '产品价格',
      dataIndex: 'prod_price',
      hideInSearch: true,
    },

    {
      title: '支付状态',
      dataIndex: 'state',
      valueEnum: {
        0: { text: '等待付款', },
        1: { text: '已完成付款', },
        2: { text: '付款超时关闭', },
        3: { text: '已退款', },
        4: { text: '已结束[不可退款]', },
        5: { text: '支付平台异常', },
      },
      hideInSearch: true,
    },
    {
      title: '支付人信息',
      dataIndex: 'payer',
      hideInSearch: true,
    },

    // transaction_id: string; // 支付平台唯一交易ID
    // customer_email: string; // 客户邮箱地址(Stripe支付必填)
    // prod_price: string; // 产品价格
    // currency: string; // 单位(CNY/USD...)
    // pay_amount: string; // 支付金额(单位: 元)
    // refund_amount: string; // 退款金额(单位: 元)
    // state: 0 | 1 | 2 | 3 | 4 | 5; // 支付状态(0=等待付款 1=已完成付款 2=付款超时关闭 3=已退款 4=已结束[不可退款] 5=支付平台异常)
    // created_time: string; // 创建时间
    // updated_time: string; // 更新时间
    // pay_url: string; // 支付链接
    // extra_data: any; // 附带数据(JSON)
    // message: string; // 支付交易信息
    // payer: string; // 支付人信息

    {
      title: '创建时间',
      dataIndex: 'created_time',
      valueType: 'dateTime',
      hideInSearch: true,
      // hideInTable: true,
    },
    // {
    //   title: '操作',
    //   dataIndex: 'option',
    //   valueType: 'option',
    //   render: (_, record) => (
    //     <>
    //       {/* <Button
    //         type="primary"
    //         icon={<EditOutlined />}
    //         onClick={() => {
    //           handleUpdateModalVisible(true);
    //           setCurrentRow(record);
    //         }}
    //       >
    //         编辑
    //       </Button> */}


    //       <Button
    //         type="primary"
    //         icon={<SyncOutlined />}
    //         onClick={() => {
    //           // handleUpdateModalVisible(true);
    //           // setCurrentRow(record);
    //           handleSync(Number(staffId))
    //         }}
    //       >
    //         同步
    //       </Button>
    //       <Divider type="vertical" />
    //       <Button
    //         type="primary"
    //         danger
    //         icon={<DeleteOutlined />}
    //         onClick={() => {
    //           showDeleteConfirm(record);
    //         }}
    //       >
    //         删除
    //       </Button>
    //     </>
    //   ),
    // },
  ];

  return (
    <PageContainer>
      <ProTable<PaymentInfo>
        headerTitle="账单列表"
        actionRef={actionRef}
        rowKey="id"
        // search={{
        //   labelWidth: 120,
        // }}
        options={{
          search: false // 隐藏高级搜索栏
        }}

        // toolBarRender={() => [
        //   <Link href={`/manage/repository/new?staffId=${staffId}`} >
        //     <Button type="primary" key="primary"
        //     // onClick={() => handleModalVisible(true)}
        //     >
        //       <PlusOutlined /> 增加知识库
        //     </Button>
        //   </Link>,
        // ]}
        params={{
          current: 0,
          // id: Number(staffId),
        }}
        request={queryBillingList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        pagination={{ pageSize: 10 }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(Number(staffId), selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      {/* <CreateUserForm
        key={'CreateUserForm'}
        onSubmit={async (value) => {

          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        createModalVisible={createModalVisible}
      /> */}

      {/* <UpdateUserForm
        key={'UpdateUserForm'}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      /> */}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false)
        }}
        closable={false}
      >
        {staffId && (
          <ProDescriptions<PaymentInfo>
            column={2}
            title={staffId}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: staffId,
            }}
            columns={columns as ProDescriptionsItemProps<PaymentInfo>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default BillingList;
