import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Space, Tag } 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 CreateForm from './components/CreateForm';
import BomConsumption from './components/BomConsumption';
import BomList from './components/BomList';
import api from './services';

const GoodsBomsManage = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const [AddBomModalVisible, handleAddBomModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState();
  const actionRef = useRef();
  const [stockGoods, setstockGoods] = useState([]);

  const [getBom, setBom] = useState();
  /** 商品配方调整新建/更新窗口的弹窗 */
  const [setBomModalVisible, handleBomModalVisible] = useState();
  const [BomConsumptionModalVisible, SetBomConsumptionModalVisible] = useState(false);

  const [bomtype, setBomtype] = useState([]);
  const [bomtypeenum, setBomtypeenum] = useState({});

  const [bomConsumptionInfo, setBomConsumptionInfo] = 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);
      });

      api.getbomtypepage({ current: 1, pagesize: 1000 }).then((r) => {
        setBomtype(r.data.data);

        let list = {};
        formateData(r.data.data);
        function formateData(datas) {
          for (var i in datas) {
            list[datas[i]['id']] = { text: datas[i]['name'] };
            if (datas[i].children) {
              formateData(datas[i].children);
            }
          }
        }
        setBomtypeenum(list);
      });
    }
    initStockGoods(); //回调原料信息
  }, []);
  /**
   * 添加节点
   *
   * @param fields
   */
  function handleAdd(fields) {
    try {
      api.add(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 fields
   */

  function handleUpdate(fields) {
    try {
      api
        .update(JSON.stringify(fields))
        .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: 'code',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '配方名称',
      dataIndex: 'name',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '配方分类',
      dataIndex: 'bomTypeList',
      search: false,
      width: 450,
      render: (_, record) => (
        <Space>
          {
            bomtype.filter(x => {
              let findId = record.bomTypeList.find(findItem => findItem === x.id);
              let findBomType = bomtype.find(bomItem => bomItem.id === findId);
              return findBomType != null || undefined;
            }).map(item => (
              <Tag color="#87d068" key={item.id}>
                {item.name}
              </Tag>
            ))}
        </Space>
      ),
    },
    // {
    //   title: '配方分类',
    //   dataIndex: 'bomType',
    //   search: false,
    //   valueEnum: bomtypeenum,
    // },
    {
      title: '配方类型',
      dataIndex: 'isMain',
      hideInForm: true,
      valueEnum: {
        false: {
          text: '辅料配方',
          status: 'Processing',
        },
        true: {
          text: '主料配方',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
        key="primary1"
        type="primary"
        onClick={() => {

          setBom(record);
          handleBomModalVisible(true);
        }}
      >
        添加配方原料
      </a>,
        <a
          key="primary3"
          type="primary"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
        // <a
        //   key="BomConsumption"
        //   type="primary"
        //   onClick={() => {
        //     setCurrentRow(record);
        //     handleAddBomModalVisible(true);
        //   }}
        // >
        //   添加配方物料
        // </a>,
        // <a
        //   key="primary2"
        //   type="primary"
        //   onClick={async () => {
        //     var r = await api.getomConsumptionInfo(record.id);
        //     setBomConsumptionInfo(r.data);
        //     setCurrentRow(record);
        //     SetBomConsumptionModalVisible(true);
        //   }}
        // >
        //   味魔方配置
        // </a>,

      ],
    },
  ];

  const onUpdateBom = (data) => {
    setBomConsumptionInfo(data);
  }

      /**
     * 删除物料
     * @param {*} itemList
     */
       const onDeleteMate = (itemList, index) => {
        const tempBom = JSON.parse(JSON.stringify(bomConsumptionInfo));
        const findIndex = tempBom[index].bomMaterials.findIndex(item => itemList.id === item.id);
        tempBom[index].bomMaterials.splice(findIndex, 1);
        setBomConsumptionInfo(tempBom);
      }

  return (
    <PageContainer>
      <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;
          await api.getpage(params).then((r) => {
            goodsBomsData = r.data.data;
            total = r.data.total;
          });
          return {
            data: goodsBomsData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
      />


      {getBom && Object.keys(getBom).length ? (
        <BomList
          onCancel={() => {
            handleBomModalVisible(false);
            setBom({});
          }}
          createModalVisible={setBomModalVisible}
          values={getBom}
        />

      ) : null}
      {/*商品配方(新增，修改) */}
      <CreateForm
        bomtype={bomtype}
        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();
            }
          }
          actionRef.current.reload();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />

      {/* 配方用量 */}
      <BomConsumption
        onFinish={async (value) => {

          api.addBomConsumptionInfo({
            "bomId": currentRow.id,
            "bomConsumptionInfo": value
          }).then((r) => {
            if (r.data) {
              SetBomConsumptionModalVisible(false);
              message.success('成功');
            } else {
              message.error('添加失败请重试！');
            }

          });
          console.log(value);
        }}
        visible={BomConsumptionModalVisible}
        values={bomConsumptionInfo}
        onUpdateBom={onUpdateBom}
        onCancel={() => {
          SetBomConsumptionModalVisible(false);
        }}
        onDeleteMate={onDeleteMate}
      />
    </PageContainer>
  );
};

export default GoodsBomsManage;
