import {
  productcontrollerCreateproduct,
  productcontrollerDeleteproduct,
  productcontrollerGetcategorieall,
  productcontrollerGetflavorsall,
  productcontrollerGetproductlist,
  productcontrollerGetstrengthall,
  productcontrollerUpdateproductnamecn,
} from '@/servers/api/product';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  PageContainer,
  ProColumns,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { App, Button, Popconfirm } from 'antd';
import React, { useRef } from 'react';

const NameCn: React.FC<{
  id: number;
  value: string;
  tableRef: React.MutableRefObject<ActionType | undefined>;
}> = ({value,tableRef, id}) => {
  const { message } = App.useApp();
  const [editable, setEditable] = React.useState<boolean>(false);
  if (!editable) return <div onClick={() => setEditable(true)}>{value||'-'}</div>; 
  return <ProFormText fieldProps={{autoFocus:true}} initialValue={value} onBlur={async(e) => {
    if(!e.target.value) return setEditable(false)
    const { success, message: errMsg } =
    await productcontrollerUpdateproductnamecn({
      id,
      nameCn: e.target.value,
    })
    setEditable(false)
    if (!success) {
      return message.error(errMsg)
    }
    tableRef?.current?.reload()
  }} />
}
const List: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const { message } = App.useApp();
  const columns: ProColumns<API.Product>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '中文名',
      dataIndex: 'nameCn',
      render: (_, record) => { 
        return (
          <NameCn value={record.nameCn} id={record.id} tableRef={actionRef} />
        )
      },
    },
    {
      title: '产品描述',
      dataIndex: 'description',
      hideInSearch: true,
    },
    {
      title: '产品分类',
      dataIndex: 'categoryName',
    },
    {
      title: '强度',
      dataIndex: 'strengthName',
    },
    {
      title: '口味',
      dataIndex: 'flavorsName',
    },
    {
      title: '湿度',
      dataIndex: 'humidity',
    },
    {
      title: 'sku',
      dataIndex: 'sku',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Popconfirm
            title="删除"
            description="确认删除？"
            onConfirm={async () => {
              try {
                const { success, message: errMsg } =
                  await productcontrollerDeleteproduct({ id: record.id });
                if (!success) {
                  throw new Error(errMsg);
                }
                actionRef.current?.reload();
              } catch (error: any) {
                message.error(error.message);
              }
            }}
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageContainer header={{ title: '产品列表' }}>
      <ProTable<API.Product>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [<CreateForm tableRef={actionRef} />]}
        request={async (params) => {
          const { data, success } = await productcontrollerGetproductlist(
            params,
          );
          return {
            total: data?.total || 0,
            data: data?.items || [],
            success,
          };
        }}
        columns={columns} 
        editable={{
          type: 'single',
          onSave: async (key, record, originRow) => {
            console.log('保存数据:', record);
          },
        }}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
    </PageContainer>
  );
};

const CreateForm: React.FC<{
  tableRef: React.MutableRefObject<ActionType | undefined>;
}> = ({ tableRef }) => {
  const { message } = App.useApp();
  return (
    <DrawerForm<API.CreateProductDTO>
      title="新建"
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建
        </Button>
      }
      autoFocusFirstInput
      drawerProps={{
        destroyOnHidden: true,
      }}
      onFinish={async (values) => {
        try {
          const { success, message: errMsg } =
            await productcontrollerCreateproduct(values);
          if (!success) {
            throw new Error(errMsg);
          }
          tableRef.current?.reload();
          message.success('提交成功');
          return true;
        } catch (error: any) {
          message.error(error.message);
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          name="name"
          label="名称"
          width="lg"
          placeholder="请输入名称"
          rules={[{ required: true, message: '请输入名称' }]}
        />
        <ProFormTextArea
          name="description"
          width="lg"
          label="产品描述"
          placeholder="请输入产品描述"
        />
        <ProFormSelect
          name="categoryId"
          width="lg"
          label="产品分类"
          placeholder="请选择产品分类"
          request={async () => {
            const { data = [] } = await productcontrollerGetcategorieall();
            return data.map((item) => ({
              label: item.name,
              value: item.id,
            }));
          }}
          rules={[{ required: true, message: '请选择产品分类' }]}
        />
        <ProFormSelect
          name="strengthId"
          width="lg"
          label="强度"
          placeholder="请选择强度"
          request={async () => {
            const { data = [] } = await productcontrollerGetstrengthall();
            return data.map((item) => ({
              label: item.name,
              value: item.id,
            }));
          }}
          rules={[{ required: true, message: '请选择强度' }]}
        />
        <ProFormSelect
          name="flavorsId"
          width="lg"
          label="口味"
          placeholder="请选择口味"
          request={async () => {
            const { data = [] } = await productcontrollerGetflavorsall();
            return data.map((item) => ({
              label: item.name,
              value: item.id,
            }));
          }}
          rules={[{ required: true, message: '请选择口味' }]}
        />
        <ProFormSelect
          name="humidity"
          width="lg"
          label="干湿"
          placeholder="请选择干湿"
          valueEnum={{
            dry: '干',
            wet: '湿',
          }}
          rules={[{ required: true, message: '请选择干湿' }]}
        />
      </ProForm.Group>
    </DrawerForm>
  );
};

export default List;
