import { PlusOutlined } from '@ant-design/icons';
import { Popconfirm, Modal, Button, message, Input, Drawer } from 'antd';
import React, { useEffect, useState, useRef } 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 {
  GetStoreBatchingStockPageAsync,
  AddStoreBatchingStocAsync,
  UpdateStoreBatchingStocAsync,
  PushStockAsync,
  CheckStockAdjust,
  removeSingleStockAdjust,
  PushDeviceTMC,
} from './services';

const key = 'message';

const DeviceStockManager = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [total, setTotal] = useState(0);
  const [deviceKey, setdeviceKey] = useState();
  //添加
  const handleAdd = async (fields) => {
    try {
      fields.DeviceId = props.values.key;
      message.loading('正在添加', key);
      await AddStoreBatchingStocAsync(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('添加成功');
          actionRef.current.reload();
          return true;
        } else {
          message.error('添加失败' + r.errors);
          actionRef.current.reload();
          return false;
        }
      });
    } catch (error) {
      message.error('添加失败请重试！');
      actionRef.current.reload();
      return false;
    }
  };

  //同步
  const pushStock = async (id) => {
    try {
      message.loading('正在同步', key);
        await PushStockAsync(id).then((r) => {
          message.destroy(key);
          if (r.data) {
            setSelectedRows([]);
            message.success('同步成功');
            actionRef.current.reload();
            return true;
          } else {
            message.error('同步失败' + r.errors);
            actionRef.current.reload();
            return false;
          }
        });

    } catch (error) {
      message.error('同步失败请重试！');
      actionRef.current.reload();
      return false;
    }
  };

  //获取实时库存
  const handleCheckStockAdjust = async (id) => {
    console.log("fdsfds");
    try {
      if (props.isbom) {
        await CheckStockTMCAdjust(id).then((r) => {
          message.destroy(key);
          if (r.data) {
            message.success('获取成功');
            actionRef.current.reload();
            return true;
          } else {
            message.error('获取失败' + r.errors);
            actionRef.current.reload();
            return false;
          }
        });
      } else {
        await CheckStockAdjust(id).then((r) => {
          message.destroy(key);
          if (r.data) {
            message.success('获取成功');
            actionRef.current.reload();
            return true;
          } else {
            message.error('获取失败' + r.errors);
            actionRef.current.reload();
            return false;
          }
        });
      }
    } catch (error) {
      message.error("获取失败！");
      actionRef.current.reload();
      return false;
    }
  };
  const handleRemoveSingle = async (value) => {
    try {
      await removeSingleStockAdjust(value).then((r) => {
        if (r.data) {
          message.success('删除成功，即将刷新');
          //刷新数据
          actionRef.current.reload();
        } else {
          message.error('删除失败，请重试');
          actionRef.current.reload();
        }
      });
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
      actionRef.current.reload();
    }
  };

  //修改
  const handleUpdate = async (fields) => {
    try {
      message.loading('正在修改', key);
      message.destroy(key);
      fields.DeviceId = props.values.key;
      await UpdateStoreBatchingStocAsync(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('修改成功');
          return true;
        } else {
          message.error('修改失败' + r.errors);
          return false;
        }
      });
    } catch (error) {
      message.error('修改失败请重试！');
      return false;
    }
  };

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '物料',
      dataIndex: 'batching_Name',
      valueType: 'textarea',
    },
    {
      title: '数量',
      dataIndex: 'batching_Count',
      valueType: 'textarea',
    },
    {
      title: '库位',
      dataIndex: 'batching_Loc',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          {' '}
          修改
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            handleRemoveSingle(record.id);
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <Modal
      width={1200}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      //(props.values == undefined ? '' : props.values.store_Name) +
      title={(props.values == undefined ? '' : props.values.title) + '库存原料调整'}
      search={false}
      visible={props.stockModalVisible}
      footer={false}
      onCancel={() => props.onCancel()}
      maskClosable={false}
    >
      <PageContainer
        header={{
          title: '',
          breadcrumb: {},
        }}
      >
        <ProTable
          headerTitle=""
          actionRef={actionRef}
          rowKey="id"
          search={false}
          toolBarRender={() => [
            <Popconfirm
              type="primary"
              key="primary"
              title="获取实时库存会覆盖本次补货数据"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                handleCheckStockAdjust(props.values.key);
              }}
              onCancel={() => { }}
            >
              <Button type="primary" key="primary">
                获取实时库存
              </Button>
            </Popconfirm>,
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                if (selectedRowsState.length == 0) {
                  message.error('请选择需要同步的数据！！');
                }
                // else if (selectedRowsState.length < 6) {
                //   message.error('必须同步6个库存位置的数据,现在条件不满足不能同步！！');
                // }
                else {
                  pushStock(props.values.key);
                  actionRef.current?.reloadAndRest?.();
                }
              }}
            >
              同步库存原料
            </Button>,
            <Button
              disabled={props.isbom && total > 14}
              type="primary"
              key="primary"
              onClick={() => {
                handleModalVisible(true);
                setdeviceKey(props.values.deviceTypeKey)
              }}
            >
              <PlusOutlined /> 新增库存原料
            </Button>,
          ]}
          request={async (params) => {
            var data = [];
            var total = 0;
            //params.DeviceId ='263971c3-38d6-43a2-a2df-bb5be147d05e'; //props.values.key;
            params.DeviceId = props.values.key;

            await GetStoreBatchingStockPageAsync(params).then((r) => {
              data = r.data.data;
              total = r.data.total;
              setTotal(total);
            });
            return {
              data: data,
              success: true,
              total: total,
            };
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />

        <CreateForm
          isbom={props.isbom}
          bomIds={props.bomIds}
          deviceKey = {props.values == undefined ? '' : props.values.deviceTypeKey}
          DeviceId={props.values == undefined ? '' : props.values.key}
          onFinish={async (value) => {
            var success = false;
            if (value.id) {
              success = handleUpdate(value);
            } else {
              success = handleAdd(value);
            }
            if (success) {
              handleModalVisible(false);
              setCurrentRow(undefined);
              actionRef.current.reload();
            }
          }}
          onCancel={() => {
            handleModalVisible(false);
            setCurrentRow(undefined);
          }}
          createModalVisible={createModalVisible}
          values={currentRow || {}}

        />
      </PageContainer>
    </Modal>
  );
};

export default DeviceStockManager;
