import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Popconfirm } 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 { history } from 'umi';
import {
  goods,
  addGoods,
  updateGoods,
  removeGoods,
  goodsType,
  getBomInfo,
  AddBomApi,
  getbompage
} from './service';

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields) => {
  console.log('fields', fields);
  const hide = message.loading('正在添加');
  fields.createBy = 'admin';
  try {
    await addGoods(JSON.stringify(fields)).then((r) => {
      if (r.data) {
        message.success('添加成功');
      } else {
        message.error('添加失败请重试！');
      }
    });
    hide();
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');
  try {
    await updateGoods({
      id: fields.id,
      code: fields.code,
      name: fields.name,
      price: fields.price,
      imgUrl: fields.imgUrl,
      remark: fields.remark,
      status: fields.status,
      goodsTypeId: fields.goodsTypeId,
    }).then((r) => {
      if (r.data) {
        message.success('配置成功');
      } else {
        message.error('配置失败请重试！');
      }
    });
    return true;
  } catch (error) {
    hide();

    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeGoods(selectedRows.map((row) => row.id)).then((r) => {
      hide();
      if (r.data) {
        message.success('删除成功，即将刷新');
      } else {
        message.error('删除失败，请重试');
      }
    });

    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const GoodsManage = () => {
  const [goodsTypes, setGoodsTypes] = useState([]);

  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);

  /** 商品配方调整*/

  const [BomType, setBomType] = useState();
  const [getGoodsBom, setGoodsBom] = useState();

  const [getGoodsBoms, setGoodsBoms] = useState();
  /** 商品配方调整新建/更新窗口的弹窗 */
  const [setGoodsBomModalVisible, handleGoodsBomModalVisible] = useState();
  /** 国际化配置 */

  useEffect(() => {
    function initBom() {

      getbompage({ current: 1, pageSize: 10000000, }).then((r) => {
        var arr = r.data.data;
        setGoodsBoms(arr);
      });
    }
    initBom(); //回调原料信息
    function initGoodsType() {
      goodsType({ current: 1, pageSize: 1000 }).then((r) => {
        var arr = r.data.data;
        arr.forEach((element) => {
          element.text = element.goodsType_Name;
          element.goodsTypeId = element.id;
        });

        setGoodsTypes(arr);
      });
    }
    initGoodsType();
  }, []);
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,

    },
    {
      title: '图片地址',
      dataIndex: 'imgUrl',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '编码',
      dataIndex: 'code',
      valueType: 'textarea',
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: '基础价格',
      dataIndex: 'price',
      hideInForm: true,
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '会员价',
      dataIndex: 'vipPrice',
      hideInForm: true,
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '商品小类',
      dataIndex: 'goodsTypeName',
      hideInForm: true,
      hideInSearch: true,
      // valueEnum: goodsTypes
    },
    {
      title: '商品类型',
      dataIndex: 'goodsTypeId',
      hideInForm: true,
      hideInTable: true,
      // hideInSearch: true,
      valueEnum: goodsTypes,
    },

    {
      title: '商品属性',
      dataIndex: 'goodsAttribute',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '单品',
        },
        1: {
          text: '套餐',
        }
      },

    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '停用',
          status: 'Error',
        },
        2: {
          text: '删除',
          status: 'Error',
        },
      },

    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="primary"
          type="primary"
          onClick={() => {
            history.push({
              pathname: '/goods/goodsInfo',
              query: {
                isAdd: false,
                values: record,
                tabStatus: 'basis'
              },
            });
            // handleModalVisible(true);
            // setCurrentRow(record);
          }}
        >
          更新
        </a>,
        <a
          key="primary"
          type="primary"
          onClick={() => {
            history.push({
              pathname: '/goods/goodsInfo',
              query: {
                isAdd: false,
                values: record,
                tabStatus: 'goodsbom'
              },
            });
            // handleModalVisible(true);
            // setCurrentRow(record);
          }}
        >
          商品配方设置
        </a>,
        record.status === 0 &&
        ((
          <a
            key="link"
            onClick={() => {
              record.status = '1';
              handleUpdate(record);
              actionRef.current.reload();
            }}
          >
            停用
          </a>
        )),
        (record.status === 1 || record.status === 2) && (
          <a
            key="warn"
            onClick={() => {
              record.status = '0';
              handleUpdate(record);
              actionRef.current.reload();
            }}
          >
            启用
          </a>
        ),
       <a
       key="config"
       onClick={() => {
         history.push({
           pathname: '/bom/cookingentry',
           query: {
             isAdd: false,
             values:record
           },
         });
       }}
     >
      小炒配置
     </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              history.push({
                pathname: '/goods/goodsInfo',
                query: {
                  isAdd: true,
                  values: null,
                  tabStatus: 'basis'
                },
              });
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var goodsData = [];
          if (params.goodsTypeId != undefined) {
            params.goodsTypeId = goodsTypes[params.goodsTypeId].goodsTypeId;
          }
          var total = 0;
          await goods(params).then((r) => {
            goodsData = r.data.data;
            // goodsData.forEach((x) => {
            //   x.status = x.status.toString();
            // });
            total = r.data.total;
          });
          return {
            data: goodsData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              {/* <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.id, 0)} 万
              </span> */}
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
        </FooterToolbar>
      )}
      <CreateForm
        goodsTypaData={goodsTypes}
        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 || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default GoodsManage;
