import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import {
  getStockItemList,
  addStockItem,
  updateStockItem,
  removeStockItem,
  getProductPage,
  getOrgPage,
  getUintList,
  getStockItem
} from './services';

//页面 相当于 class
const StockItemManage = () => {
  //机构变量
  const [orgEnum, setOrgEnum] = useState();
  const [orgArray, setOrgArray] = useState([]);

  //物料变量
  const [productEnum, setProductEnum] = useState();
  const [productArray, setProductArray] = useState([]);

  const [uintListEnum, setUintEnum] = useState();

  //初始化数据
  useEffect(() => {
    //初始化物料
    const initProduct = (val) => {
      var data = getProductPage({ current: 1, pageSize: 1000 }).then((data) => {
        var list = {};
        let list2 = [];
        data.data.data.forEach((item) => {
          list2.push({
            text: item.name,
            id: item.id,
          });
          list[item.id] = { text: item.name };
        });

        setProductArray(list2);
        setProductEnum(list);
      });
    };

    //初始化机构
    const initOrg = (val) => {
      var data = getOrgPage({ current: 1, pageSize: 1000 }).then((data) => {
        var list = {};
        let list2 = [];
        data.data.data.forEach((item) => {
          list2.push({
            text: item.name,
            id: item.id,
          });
          list[item.id] = { text: item.name };
        });

        setOrgArray(list2);
        setOrgEnum(list);
      });
    };

    //初始化包装单位
    const initUintList = (val) => {
      var data = getUintList().then((data) => {
        var list = {};
        data.data.forEach((item) => {
          list[item.id] = { text: item.name };
        });
        setUintEnum(list);
      });
    };

    initProduct();
    initOrg();
    initUintList();
  }, []);

  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [showDetail, setShowDetail] = useState(false);
  //绑定
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();

  //选中的行
  const [selectedRowsState, setSelectedRows] = useState([]);

  /**
   * 添加节点
   *
   * @param fields
   */
  function handleAdd(fields) {
    message.loading('正在添加');
    try {
      addStockItem(JSON.stringify(fields));
      message.success('添加成功');
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  }

  /**
   * 更新节点
   *
   * @param fields
   */

  function handleUpdate(fields) {
    try {
      updateStockItem(JSON.stringify(fields)).then((r) => {
        if (r.data) {
          message.success('配置成功');
          actionRef.current.reload();
        } else {
          message.error('配置失败请重试！');
        }
      });
      return true;
    } catch (error) {
      message.error('配置失败请重试！');
      return false;
    }
  }

  /**
   * 批量删除节点
   *
   * @param selectedRows
   */
  function handleRemove() {
    try {
      removeStockItem(selectedRowsState.map((item, index) => item.id)).then((r) => {
        if (r.data) {
          message.success('删除成功，即将刷新');
        } else {
          message.error('删除失败，请重试');
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
    }
  }

  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '机构名称',
      dataIndex: 'orgId',
      valueEnum: orgEnum,
    },
    {
      title: '物料名称',
      dataIndex: 'productId',
      valueEnum: productEnum,
    },
    {
      title: '库存数量',
      dataIndex: 'stockQty',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '库存单位',
      dataIndex: 'stockUint',
      valueEnum: uintListEnum,
      hideInSearch: true,
    },
    {
      title: '物料编码',
      dataIndex: 'code',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createAt',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {

            getStockItem(record.id).then((r) => {

              if (r.data) {
                handleModalVisible(true);
                setCurrentRow(() => {
                  record.productList = r.data;
                  return record;
                });
              }
            });

          }}
        >
          更新
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="物料入库"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
              setCurrentRow({});
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        //数据绑定
        request={async (params) => {
          var stockItemData = [];
          var total = 0;
          await getStockItemList(params).then((r) => {
            stockItemData = r.data.data;
            total = r.data.total;
          });
          return {
            data: stockItemData,
            success: true,
            total: total,
          };
        }}
        // 每行选择点击事件
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      ></ProTable>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={() => {
              handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            type="primary"
            key="primary"
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      {/* 库存管理(新增，修改) */}
      <CreateForm
        productArray={productArray}
        orgArray={orgArray}
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default StockItemManage;
