import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Modal } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import api from './services';

const BomReplace = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);

  // //获取商品数据
  const [goods, setgoods] = useState([]);

  //获取原料名称
  const [stockGoods, setstockGoods] = useState([]);
  // 监控数据变化
  useEffect(() => {
    /** 获取原料名称*/
    function initStockGoods() {
      api.postStockGoods().then((r) => {
        var arr = r.data;
        arr.forEach((element) => {
          element.text = element.name;
          element.stockGoodsId = element.id;
        });
        setstockGoods(arr);
      });
    }
    initStockGoods(); //回调原料信息
  }, []);

  /**
   * 添加节点
   *
   * @param fields
   */
  function handleAdd(fields) {
    try {
      api
        .addGoodsBom({
          itemId: fields.itemId,
          price: fields.price,
          goodsbomId: props.values.id,
          replaceId: props.values.batchingId,
        })
        .then((r) => {
          if (r.data) {
            message.success('添加成功');
            //刷新数据
            actionRef.current.reload();
          } else {
            message.error('添加失败请重试！');
          }
        });
      return true;
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  }
  /**
   * 更新节点
   *
   * @param fields
   */

  function handleUpdate(fields) {
    console.log('传参数据', fields);
    try {
      api
        .updateGoodsBom({
          id: fields.id,
          status: fields.status,
          itemId: fields.itemId,
          price: fields.price,
          goodsbomId: props.values.id,
          replaceId: props.values.stockGoodsCode,
        })
        .then((r) => {
          if (r.data) {
            message.success('配置成功');
          } else {
            message.error('配置失败请重试！');
          }
          //刷新数据
          actionRef.current.reload();
        });
      return true;
    } catch (error) {
      message.error('配置失败请重试！');
      return false;
    }
  }

  /**
   * 删除节点
   *
   *
   */

  function handleRemove() {
    if (!selectedRowsState) return true;
    try {
      api.removeGoodsBom(selectedRowsState.map((row) => row.id)).then((r) => {
        if (r.data) {
          message.success('删除成功，即将刷新');
        } else {
          message.error('删除失败，请重试');
        }
        //刷新数据
        actionRef.current.reload();
      });
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
      return false;
    }
  }

  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,
      tip: '规则名称是唯一的 key',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '原料名称',
      dataIndex: 'name',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      valueType: 'money',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '停用',
          status: 'Error',
        },
        2: {
          text: '删除',
          status: 'Error',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        record.status === 0 && (
          <a
            key="link"
            onClick={() => {
              record.status = '1';
              handleUpdate(record);
            }}
          >
            停用
          </a>
        ),
        (record.status === 1 || record.status === 2) && (
          <a
            key="warn"
            onClick={() => {
              record.status = '0';
              handleUpdate(record);
            }}
          >
            启用
          </a>
        ),
        <a
          key="primary"
          type="primary"
          onClick={() => {
            setCurrentRow(record);
            handleModalVisible(true);
          }}
        >
          更新
        </a>,
      ],
    },
  ];

  return (
    <Modal
      width={1200}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="配方物料替换"
      visible={props.createModalVisible}
      footer={false}
      onCancel={() => props.onCancel()}
      maskClosable={false}
    >
      <ProTable
        headerTitle="替换物料列表"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 20 }}
        search={false}
        toolBarRender={() => [
          <Button type="primary" key="create" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新增配方替换物料
          </Button>,
        ]}
        //数据绑定
        request={async (params) => {
          var goodsBomsData = [];
          var total = 0;
          //商品编号
          if (props.values.id != undefined) {
            params['goodsbomId'] = props.values.id;
            params['replaceId'] = props.values.stockGoodsCode;
          }
          await api.goodsBoms(params).then((r) => {
            goodsBomsData = r.data.data;
            total = r.data.total;
          });
          return {
            data: goodsBomsData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
      />
      {/*商品配方(新增，修改) */}
      <CreateForm
        stockGoodsData={stockGoods}
        onFinish={async (value) => {
          var success = false;

          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
    </Modal>
  );
};

export default BomReplace;
