import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Popconfirm, Upload, Spin } 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 { history } from 'umi';
import { getDataBaseUrl } from '@/global_data';
import {
  goods,
  removeGoods,
  gettree,
} from './service';

/**
 * 删除节点
 *
 * @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 [treeData, setTreeData] = useState();
  const [loading, setLoading] = useState(false);
  /** 国际化配置 */
  useEffect(() => {
    //function initBom() {

    //   getbompage({ current: 1, pageSize: 10000000, }).then((r) => {
    //     var arr = r.data.data;
    //     setGoodsBoms(arr);
    //   });
    // }
    // initBom(); //回调原料信息
   
    initGoodsType();
  }, []);
  function initGoodsType() {
    gettree().then((r) => {
      setTreeData(r.data);
    });
  }
  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: 'goodsTypeName',
      valueType: 'treeSelect',
      fieldProps: {
        showSearch:true,
        allowClear:true,
        options: treeData
      },
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createAt',
    //   valueType: 'date',
    // },
    {
      title: '备注',
      dataIndex: 'descritption',
      ellipsis: true,
      tip: '标题过长会自动收缩',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 350,
      render: (_, record) => [
        <a
          key="primary"
          type="primary"
          onClick={() => {
            history.push({
              pathname: '/database/goods/goodsInfo',
              query: {
                isAdd: false,
                values: record,
                tabStatus: 'basis'
              },
            });
            // handleModalVisible(true);
            // setCurrentRow(record);
          }}
        >
          更新
        </a>,
        <a
          key="primary"
          type="primary"
          onClick={() => {
            history.push({
              pathname: '/database/goods/goodsbom',
              query: {
                isAdd: false,
                values: record,
                tabStatus: 'goodsbom'
              },
            });
            // handleModalVisible(true);
            // setCurrentRow(record);
          }}
        >
          商品配方设置
        </a>,
            <a
            key="primary"
            type="primary"
            onClick={() => {
              history.push({
                pathname: '/database/goods/goodstechnology',
                query: {
                  isAdd: false,
                  values: record,
                  tabStatus: 'goodstechnologymaken'
                },
              });
              // handleModalVisible(true);
              // setCurrentRow(record);
            }}
          >
            商品工艺设置
          </a>,
    
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            removeGoods(record.id).then((r) => {
              if (r.succeeded) {
                message.success('删除成功');
                actionRef.current.reloadAndRest();
              } else {
                message.error(r.errors);
              }
            });
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
         
        // <a
        //   key="config"
        //   onClick={() => {
        //     history.push({
        //       pathname: '/bom/cookingentry',
        //       query: {
        //         isAdd: false,
        //         values: record
        //       },
        //     });
        //   }}
        // >
        //   小炒配置
        // </a>,
      ],
    },
  ];
  const props = {
    beforeUpload: (file) => {
      setLoading(true);
      if (
        file.type !== 'application/vnd.ms-excel' &&
        file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ) {
        message.error(`${file.name} 不是 exelce 文件`);
      }
      return file.type == 'application/vnd.ms-excel' ||
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ? true
        : Upload.LIST_IGNORE;
    },
    name: 'file',
    action: getDataBaseUrl()+'/api/goods/exportgood',
    headers: {
      // authorization: 'authorization-text',
      Authorization: 'Bearer  ' + localStorage.getItem('token')
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        setLoading(false);
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        setLoading(false);
        message.error(`${info.file.name}:${info.file.response} `);
      }
    }
  };

  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <Spin spinning={loading} tip="上传中...">
        <ProTable
          headerTitle=""
          actionRef={actionRef}
          rowKey="id"
          pagination={{ defaultPageSize: 10 }}
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                history.push({
                  pathname: '/database/goods/goodsInfo',
                  query: {
                    isAdd: true,
                    values: null,
                    tabStatus: 'basis'
                  },
                });
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
            <Button
              key="primary"
              onClick={async () => {
                // const response = await  GoodsTemplateExport();
                // const blob = new Blob([response]);
                // const url = URL.createObjectURL(blob);
                // console.log(blob, url);
                // const link = document.createElement('a');
                // link.download = `商品导入模板_${new Date(Date.now()).toLocaleString()}.xls`;
                // link.href = url;
                // link.click();
                const link = document.createElement('a');
                link.href = "https://hbl-test-1305371387.cos.ap-chengdu.myqcloud.com//Franchisee/goods/133463060115739076.xlsx";
                link.click();
              }}
            >
              <UploadOutlined /> 下载商品导入模板
            </Button>,
            //   <Popconfirm
            //   type="primary"
            //   key="primary"
            //   title="导入后重复数据将被替换"
            //   okText="是"
            //   cancelText="否"
            //   onConfirm={() => {
            //     handleRemove([record.id]);
            //     actionRef.current?.AndRest();
            //   }}
            //   onCancel={() => {}}
            // >

            // </Popconfirm>
            <Upload {...props} showUploadList={false}  >
              <Button icon={<UploadOutlined />} >导入商品</Button>
            </Upload>


          ]}
          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;
              console.log(goodsData)
              goodsData.forEach((x) => {
                if (x.defaultMate != null) {
                  x.defaultMate = x.defaultMate.split(",");
                }

              });
              console.log(goodsData)
              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?.AndRest?.();
              }}
            >
              删除
            </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.reloadAndRest();
            }
          }
          actionRef.current.reloadAndRest();
        }}
        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>
      </Spin>
    </PageContainer>
  );
};

export default GoodsManage;
