
// 料仓基础信息

import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Select, Tag } from 'antd';
import { useRef, useState, useEffect } from 'react';
// import { history } from '@umijs/max';
import StockInfoAPI from '@/api/StockService';
import materialAPI from '@/api/materialService'

// import RecipeAPI from '@/api/recipeService'
// import { TransferDirection } from 'antd/es/transfer';


// interface RecordType {
//   key: string;
//   title: string;
//   description: string;
//   chosen: boolean;
// }
// let selectRecordId :string;
export default () => {
  //表单
  const [typeForm] = Form.useForm();

  //下拉列表
  // const [isMaterialModalOpen, setIsMaterialModalOpen] = useState(false);
  const [modelTitle, setModelTitle] = useState<string>();
  //编辑/新增弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  const actionRef = useRef<ActionType>();
  // 下拉的状态变量
  const [RegionData, setRegionData] = useState([]);

  const columns: ProColumns<StockTypes.Info>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tooltip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '料仓名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '料仓原料',
      dataIndex: 'materialName',
      ellipsis: true,
      hideInSearch: true
    },
    {
      title: '料仓编号',
      dataIndex: 'code',
      // hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '料仓容积',
      dataIndex: 'volume',
      ellipsis: true,
      hideInSearch: true,
    },
    
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed:'right',
      render: (_, record) => [
        <Button
          key="edit"
          type="primary" size='small'
          onClick={async () => {
            setIsModalOpen(true);
            setModelTitle('编辑信息');
            const copyFormData = JSON.parse(JSON.stringify(record));
            copyFormData.state = copyFormData.state === '0';
            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑
        </Button>,

        <Popconfirm
          key="del"
          title="确定要删除此条数据吗？"
          onConfirm={() => {

            const EnablejsonData: StockTypes.Info = {
              id: record.id,
              name: '',
              code: '',
              lineId: '',
              materialName: '',
              materialId: '',
              volume: undefined
            };

            StockInfoAPI.Del(EnablejsonData).then((r: MyResponse.Content) => {
              if (r.statusCode === 200) {
                message.success(r.statusCode === 200 ? '删除成功' : r.message);
                actionRef.current?.reload();
              }
            });
          }}
          onCancel={() => {
            message.info('已取消删除');
          }}
          okText="确认"
          cancelText="关闭"
        >
          <Button type="primary" danger size='small'>删除</Button>
        </Popconfirm>,
      ],
    },
  ];

  /*
   初始化
  */
  useEffect(() => {
    // 下拉列表信息
    const RegionDataList = async () => {

      const data = await materialAPI.selectlist();
      // console.log(data);

      setRegionData(data.data);
    };
    RegionDataList();
  }, []);
  /*
   *表单提交
   */
  const OnSubmit = async (values: StockTypes.Info) => {
    console.log('values', values);
    if (values.id) {
      const response = await StockInfoAPI.Update(values);
      if (response.statusCode === 200) {
        message.success('修改成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '修改失败');
      }
    } else {
      const response = await StockInfoAPI.Add(values);
      console.log('response', response);
      if (response.statusCode === 200) {
        message.success('添加成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '添加失败');
      }
    }
  };


  return (
    <>
      <ProTable<StockTypes.Info>
        key="myTable"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        bordered
        scroll={{ x: true }}
        rowClassName={(record: any, index: number, indent: number) => {
            if (index % 2 === 0) {
                return ''; // 偶数行的类名
            } else {
                return 'even-row-background'; // 奇数行的类名
            }
        }}
        request={async (params = {}) => {
          const jsonData: StockTypes.Page = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
            id: '',
            code: params.code
          };
          const response = await StockInfoAPI.PagedList(jsonData);
          console.log(response);

          if (response.statusCode === 200) {
            return {
              data: response.data.items,
              success: true,
              total: response.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger:false
        }}
        dateFormatter="string"
        headerTitle="料仓列表"
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              typeForm.resetFields();
              setIsModalOpen(true);
              setModelTitle('新增料仓');
            }}
          >
            新建料仓
          </Button>,
        ]}
      />
      <Modal
        maskClosable={false}
        key="01"
        width={800}
        title={<Tag color="#cd201f">{modelTitle}</Tag>}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setIsModalOpen(false);
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="stockForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form
          form={typeForm}
          name="basic"
          id="stockForm"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 12 }}
          onFinish={OnSubmit}
          autoComplete="off"
        >
          <Form.Item label="id" name="id" hidden>
            <Input />
          </Form.Item>

          <Form.Item
            label="料仓名称"
            name="name"
            rules={[{ required: true, message: '此项为必填项!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="料仓原料" name="materialId" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Select placeholder='请选择原料'>
              {RegionData.map((item: MySelectType.Select) => {
                console.log(item);

                return <Select.Option value={item.key} key={item.key}>
                  <span>{item.value}</span>
                </Select.Option>
              })}
            </Select>
          </Form.Item>

          <Form.Item label="料仓编号" name="code" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Input />
          </Form.Item>
          <Form.Item label="料仓容积" name="volume" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Input />
          </Form.Item>


        </Form>
      </Modal>


    </>
  );
};
