import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal } 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 api from '../services';
import BomReplace from '../../bomreplace';
import AddBomInfo from './AddBomInfo';

const BomList = (props) => {
  /** 新建/更新窗口的弹窗 */
  const actionRef = useRef();

  const [BomReplaclVisible, BomReplacVisible] = useState(false);
  const [AddBomModalVisible, handleAddBomModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = 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.value;
        });
        setstockGoods(arr);
      });
    }
    initStockGoods(); //回调原料信息
  }, []);
  /**
   * 更新节点
   *
   * @param fields
   */

  function handleUpdate(fields) {
    try {
      api
        .deleteentry({
          id: fields.id,
        })
        .then((r) => {
          if (r.data) {
            message.success('配置成功');
          } else {
            message.error('配置失败请重试！');
          }
          //刷新数据
          actionRef.current.reload();
        });
      return true;
    } catch (error) {
      message.error('配置失败请重试！');
      return false;
    }
  }

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

  function handleEnable(fields, IsReplace) {
    try {
      api
        .Enable({
          id: fields.id,
          IsReplace: IsReplace,
        })
        .then((r) => {
          if (r.data) {
            message.success('操作成功');
          } else {
            message.error('操作失败请重试！');
          }
          //刷新数据
          actionRef.current.reload();
        });
      return true;
    } catch (error) {
      message.error('操作失败请重试！');
      return false;
    }
  }
/**
  * 添加节点
  *
  * @param fields
  */
 function handleAddEntry(fields) {
  try {
    api.addentry(JSON.stringify(fields)).then((r) => {
      if (r.data) {
        message.success('添加成功');
        //刷新数据
        actionRef.current.reload();
      } else {
        message.error('添加失败请重试！');
      }
    });
    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: 'batchingName',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '配方用量',
      dataIndex: 'bomQty',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '是否可以替换',
      dataIndex: 'isReplace',
      hideInForm: true,
      valueEnum: {
        false: {
          text: '不可替换',
          status: 'Processing',
        },
        true: {
          text: '可替换',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        record.isReplace && (
          <a
            key="link1"
            onClick={() => {
              BomReplacVisible(true);
              setCurrentRow(record);
            }}
          >
            替换物料
          </a>
        ),
        record.isReplace && (
          <a
            key="link2"
            onClick={() => {
              handleEnable(record, 0);
            }}
          >
            禁用替换
          </a>
        ),
        !record.isReplace && (
          <a
            key="link3"
            onClick={() => {
              handleEnable(record, 1);
            }}
          >
            启用替换
          </a>
        ),
        <a
          key="link4"
          onClick={() => {
            handleUpdate(record);
          }}
        >
          删除
        </a>
      ],
    },
  ];
  return (
    <Modal
      title={'查看' + props.values.name + '配方原料'}
      width={640}
      visible={props.createModalVisible}
      bodyStyle={{ padding: '32px 40px 48px' }}
      footer={null}
      onCancel={() => {
        props.onCancel();
      }}
      destroyOnClose
    >
      <ProTable
        headerTitle="商品配方信息查询"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 20 }}
        search={false}
        toolBarRender={() => [
          <Button type="primary" key="create" onClick={() => handleAddBomModalVisible(true)}>
            <PlusOutlined /> 添加配方原料
          </Button>,
        ]}
        //数据绑定
        request={async (params) => {
          var goodsBomsData = [];
          var total = 0;
          if (props.values.id != undefined) {
            params['bomId'] = props.values.id;
          }
          await api.getentrypage(params).then((r) => {
            goodsBomsData = r.data.data;
            total = r.data.total;
          });
          return {
            data: goodsBomsData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
      />
      {/**物料替换 */}
      <BomReplace
        // stockGoodsData={stockGoods}
        // onFinish={async (value) => {
        //   var success = false;
        //   value['goodsId'] = props.values.id;
        //   if (value.id) {
        //     success = await handleUpdate(value);
        //   } else {
        //     success = await handleAdd(value);
        //   }
        //   if (success) {
        //     BomReplacVisible(false);
        //     setCurrentRow(undefined);

        //     if (actionRef.current) {
        //       actionRef.current.reload();
        //     }
        //   }
        // }}
        onCancel={() => {
          BomReplacVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={BomReplaclVisible}
        values={currentRow || {}}
      />
       {/*商品配方(新增，修改) */}
       <AddBomInfo
        onFinish={async (value) => {
          value['bomId'] = props.values.id;
          var success = false;
          success = await handleAddEntry(value);
          if (success) {
            handleAddBomModalVisible(false);
          }
          actionRef.current.reload();
        }}
        onCancel={() => {
          handleAddBomModalVisible(false);
        }}
        createModalVisible={AddBomModalVisible}
        stockGoodsData={stockGoods}
      />
    </Modal>
  );
};

export default BomList;
