import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Space, Tag, Popconfirm, Form } 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 { bomPage, getproductpage, GetbomTypelist, AddBom, UpdateBomInfo, UpdateBomBatcing,DelBom } from './services';
import CreateBom from './components/CreateBom';
import UpdateBom from './components/UpdateBom';
import BomBatching from './components/BomBatching'


const GoodsBomsManage = (props) => {
  const actionRef = useRef();
  const [modalVisible, setModalVisible] = useState(false);
  const [updateModalVisible, setupdateModalVisible] = useState(false);
  const [matedata, setMatedata] = useState([]);
  const [bomTypeData, setbomTypeData] = useState([]);
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [BomId, setBomId] = useState();
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [currentRow, setCurrentRow] = useState();
  const [BomBatchingVisible, setBomBatchingVisible] = useState(false);


  useEffect(() => {
    initGetbomType();
    intBatching();//默认原料
  }, []);

  function intBatching() {
    getproductpage().then((r) => {
      setMatedata(r.data);
    });
  }
  function initTypeList() {
    initGetbomType();
  }
  function initGetbomType() {
    GetbomTypelist().then((r) => {
      var list = [];
      if (r.data.length > 0) {
        r.data.forEach((item) => {
          list.push({ text: item.name, value: item.id, label: item.name });
        });
      }
      setbomTypeData(list)
    })

  }
  function initGetbomType() {
    GetbomTypelist().then((r) => {
      var list = [];
      if (r.data.length > 0) {
        r.data.forEach((item) => {
          list.push({ text: item.name, value: item.id, label: item.name });
        });
      }
      setbomTypeData(list)
    })

  }

  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',
      width: 300,
      hideInForm: true,
      hideInSearch: false,
    },
    {
      title: '配方分类',
      dataIndex: 'bomTypeList',
      search: false,

      render: (_, record) => (
        <Space>
          {
            bomTypeData.filter((x) => {
              let findId = record.bomTypeList.find((findItem) => findItem === x.value);
              let findBomType = bomTypeData.find((bomItem) => bomItem.value === findId);
              return findBomType != null || undefined;
            }).map((item) => (
              <Tag color="#87d068" key={item.value}>
                {item.text}
              </Tag>
            ))}
        </Space>
      ),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 250,
      render: (_, record) => [
        <a
          key="primary3"
          type="primary"
          onClick={() => {
            setCurrentRow(record);
            form2.setFieldsValue(record);
            setupdateModalVisible(true);
          }}
        >
          更新
        </a>,
        <a
          key="primary1"
          type="primary"
          onClick={() => {
            setBomBatchingVisible(true);
            setBomId(record.id)
          }}
        >
          配方详情
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="删除后可能影响商品配方,确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            const hide = message.loading('正在删除');
            try {
              DelBom(record.id);
              hide();
              message.success('删除成功，即将刷新');
              actionRef.current.reloadAndRest();
              return true;
            } catch (error) {
              hide();
              message.error('删除失败，请重试');
              actionRef.current.reloadAndRest();
              return false;
            }
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,

      ],
    },
  ];

  const onUpdateBomSave = () => {
    form2
      .validateFields()
      .then((values) => {
        console.log(values)
        var parm = { id: values.id, name: values.bomName, IsMain: values.bomType == '1' ? true : false, bomTypeIds: values.bomTypeList }
        UpdateBomInfo(parm).then((r) => {
          if (r.data) {
            message.success('修改成功');
            setupdateModalVisible(false);
            actionRef.current.reload();
            setBomId('')
          } else {
            message.error(r.errors || "修改失败");
          }
        })
      })
  }


  const onBomBatchingCancel = () => {
    setBomBatchingVisible(false);
    setBomId('')
  }

  const onBomBatchingFinish = (form) => {
    console.log("form", form)
    var parm = { bomId: BomId, bomEntry: form };
    UpdateBomBatcing(parm).then((r) => {
      if (r.succeeded) {
        message.success('修改成功');
        setBomBatchingVisible(false);
        actionRef.current.reload();
        setBomId('')
      } else {
        message.error(r.errors);
      }
    })
  }


  return (
    <PageContainer header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}

        request={async (params) => {
          var total = 0;
          var data = [];
          const res = await bomPage(params);
          if (res.statusCode == 200) {
            data = res.data.data;
            total = res.data.total;
          }
          return {
            data: data,
            success: true,
            total: total,
          };

        }}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />

      {/* 新增菜谱 */}
      <CreateBom modalVisible={modalVisible}
        matedata={matedata}
        form={form}
        bomTypeData={bomTypeData}
        initTypeList={initTypeList}
        onFinish={async (value) => {
          await AddBom(value).then((r) => {
            if (r.data) {
              message.success("添加成功")
              setModalVisible(false);
            } else {
              message.error("添加失败")
            }
            actionRef.current.reloadAndRest();
          })
        }}
        onCancel={() => { setModalVisible(false); form.resetFields(); }}
      />

      {/* 修改菜谱 */}
      <UpdateBom
        updateModalVisible={updateModalVisible}
        onUpdateBomSave={onUpdateBomSave}
        values={currentRow || {}}
        form={form2}
        bomTypeData={bomTypeData}
        onFinish={async (value) => {

        }}
        onCancel={() => {
          setupdateModalVisible(false);
          setCurrentRow(undefined);
        }}
      />

      {/* 配方详情 */}
      <BomBatching BomBatchingVisible={BomBatchingVisible}
        matedata={matedata}
        onBomBatchingCancel={onBomBatchingCancel}
        BomId={BomId}
        onBomBatchingFinish={onBomBatchingFinish} />


    </PageContainer>
  );
};

export default GoodsBomsManage;
