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 CreateForm from './components/CreateForm';
import GoodsBomReplace from '../goods-bom-replace';

import api from './services';

const GoodsBomsManage = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const [BomReplaclVisible, BomReplacVisible] = useState(false);
  /** 分布更新窗口的弹窗 */
  const [dicData, setDicData] = useState([]);
  const [dicDataAny, setDicDataAny] = useState([]);
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);

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

  //获取原料名称
  const [stockGoods, setstockGoods] = useState([]);
  // 监控数据变化
  useEffect(() => {
    function initgoods() {
      api.goodList({ current: 1, pageSize: 20, status: '0' }).then((r) => {
        var arr = r.data.data;
        arr.forEach((element) => {
          element.text = element.name;
          element.goodsId = element.id;
        });

        setgoods(arr);
      });
    }
    initgoods();
    /** 获取原料名称*/
    function initStockGoods() {
      api.postStockGoods().then((r) => {
        var arr = r.data;
        arr.forEach((element) => {
          element.text = element.name;
          element.stockGoodsId = element.value;
        });
        setstockGoods(arr);
      });
    }
    initStockGoods(); //回调原料信息
    function intDicData() {
      api.GetDicList('BatchingType').then((r) => {
        var arr = r.data;
        // arr.forEach((element) => {
        //   //element.text = element.remark;
        //  // element.batchingTypeId = element.value;
        // });
        let data = {};
        if (r.succeeded) {
          arr.forEach((item) => {
            data[item.value] = { text: item.remark };
          });
        }
        //setDicDataAny(data);
        console.log(arr);
        setDicData(arr);
      });
    }
   // intDicData();
  }, []);

  /**
   * 添加节点
   *
   * @param fields
   */
  function handleAdd(fields) {
    try {
      api.addGoodsBom(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) {
    console.log(fields);
    try {
      api
        .updateGoodsBom({
          id: fields.id,
          goodsID: fields.goods_Id,
          stockGoodsCode: fields.stockGoodsCode,
          remark: fields.remark,
          status: fields.status,
          batchingType: fields.batchingType,
          isReplace: fields.isReplace,
          isMain: fields.isMain,
          bomQty: fields.bomQty
        })
        .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: 'stockGoodsName',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '原料名称',
      dataIndex: 'stockGoodsCode',
      hideInForm: true,
      hideInTable: true,
      valueType: 'select',
      valueEnum: stockGoods,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '停用',
          status: 'Error',
        },
        2: {
          text: '删除',
          status: 'Error',
        },
      },
    },
    {
      title: '主要原料',
      dataIndex: 'isMain',
      hideInForm: true,
      valueEnum: {
        false: {
          text: '辅料',
          status: 'Processing',
        },
        true: {
          text: '主料',
          status: 'Success',
        },
      },
    },
    {
      title: '配方用量',
      dataIndex: 'bomQty',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '是否可以替换',
      dataIndex: 'isReplace',
      hideInForm: true,
      valueEnum: {
        false: {
          text: '不可替换',
          status: 'Processing',
        },
        true: {
          text: '可替换',
          status: 'Success',
        },
      },
    },

    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
    },
    {
      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>
        ),
        record.status === '0' && record.isReplace && (
          <a
            key="link"
            onClick={() => {
              record.isReplace = false;
              handleUpdate(record);
            }}
          >
            不启用
          </a>
        ),
        record.status === '0' && !record.isReplace && (
          <a
            key="warn"
            onClick={() => {
              record.isReplace = true;
              handleUpdate(record);
            }}
          >
            启用替换
          </a>
        ),
        record.status === '0' && record.isReplace && (
          <a
            key="link"
            onClick={() => {
              BomReplacVisible(true);
              setCurrentRow(record);
            }}
          >
            替换物料
          </a>
        ),
        <a
          key="link"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
      ],
    },
  ];

  return (
    <Modal
      width={1200}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="商品配方"
      visible={props.setGoodsBomModalVisible}
      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['goodsId'] = props.values.id;
          }
          await api.goodsBoms(params).then((r) => {
            goodsBomsData = r.data.data;
            total = r.data.total;
          });
          return {
            data: goodsBomsData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
      />
      {/*商品配方(新增，修改) */}
      <CreateForm
        dicData={dicData}
        stockGoodsData={stockGoods}
        onFinish={async (value) => {
          var success = false;
          value['goodsId'] = props.values.id;
          value['goods_Id'] = props.values.id;
          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 || {}}
      />
      {/**物料替换 */}
      <GoodsBomReplace
        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 || {}}
      />
    </Modal>
  );
};

export default GoodsBomsManage;
