import React, { useState, useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { ProTable } from '@ant-design/pro-components';
import { Button, notification } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { takeawayGoodsColumn } from './staticData/goods';
import utilStyle from '@/utils/utils.less';
import {
  apiTakeawayList,
  apiSelPickSelfList,
  apiTakeawayGoodsDel,
  apiMealInfoUpdate,
} from './service';
import { getEnterpriseList, getEnterpriseName } from './service/bll';
import SaleDateModal from './components/SaleDateModal';
import SaleSectionModal from './components/SaleSectionModal';
import GoodPriceModal from './components/GoodPriceModal';
import GoodSortModal from './components/GoodSortModal';
import { getToUrlQuery } from '@/utils/utils';

// 企业外卖商品
const TakeawayGoods = () => {
  const history = useHistory();
  const refTable = useRef();
  const [pageLoaded, setPageLoaded] = useState(false); // 可售日期弹窗
  const [visibleSaleDate, setVisibleSaleDate] = useState(false); // 可售日期弹窗
  const [visibleSaleSection, setVisibleSaleSection] = useState(false); // 可售餐段弹窗
  const [visiblePrice, setVisiblePrice] = useState(false); // 修改企业商品价格弹窗
  const [visibleSort, setVisibleSort] = useState(false); // 商品排序弹窗
  const [enterprises, setEnterprises] = useState(null); // 企业列表
  const [activeKey, setActiveKey] = useState(''); // 自提点ID
  const [enterpriseId, setEnterpriseId] = useState(''); // 企业ID
  const [pickSelfList, setPickSelfList] = useState([]); // 取餐点列表
  const [recordID, setRecordID] = useState(''); // 编辑的记录ID
  const [editItem, setEditItem] = useState({}); // 编辑的记录信息

  // 刷新列表
  const onRefresh = isReset => {
    if (!pageLoaded) {
      return;
    }
    if (isReset) {
      refTable?.current?.reloadAndRest();
    } else {
      refTable?.current?.reload();
    }
  };

  // 搜索商品列表
  const searchList = async params => {
    if (params.createDate && params.createDate.length) {
      const [startDateTime, endDateTime] = params.createDate;
      params.startDateTime = startDateTime;
      params.endDateTime = endDateTime;
    }
    const data = {
      page: params.current || 1,
      size: params.pageSize || 10,
      data: Object.assign({}, params, {
        enterpriseId,
        pickSelfId: activeKey,
      }),
    };
    const res = await apiTakeawayList(data);
    if (res && res.records) {
      return {
        data: res.records || [],
        total: res.total || 0,
      };
    }
    return {
      data: [],
      total: 0,
    };
  };
  // 删除商品
  const onDel = async id => {
    await apiTakeawayGoodsDel({
      id,
    });
    refTable.current.reload();
    notification.success({
      message: '删除成功',
    });
  };
  // 跳转添加商品
  const toAdd = async () => {
    const params = getToUrlQuery();
    const query = Object.assign(
      {
        id: enterpriseId,
        name: getEnterpriseName(enterprises, enterpriseId),
      },
      params,
    );
    history.push({
      pathname: '/takeawayGoodsInfo',
      query,
    });
  };
  // 修改商品是否列出
  const onChangeFlag = async (id, checked) => {
    const params = {
      id,
      showFlag: checked ? 1 : 0,
    };
    await apiMealInfoUpdate(params);
    notification.success({ message: '保存成功' });
    onRefresh();
  };

  // 根据企业ID获取取餐点
  const getPickSelf = async id => {
    const res = await apiSelPickSelfList({ enterpriseId: id });
    const arr =
      res?.data?.map(item => ({
        key: `${item.pickSelfId}`,
        label: <span>{item.pickSelfName}</span>,
      })) || [];
    setPickSelfList(arr);
    const [obj] = res?.data || [];
    const pid = `${obj?.pickSelfId || ''}`;
    setActiveKey(`${pid}`);
    if (pageLoaded) {
      onRefresh(true);
    }
  };

  // 改变企业
  const onChangeEnterprise = v => {
    setEnterpriseId(v);
    getPickSelf(v);
  };

  // 获取企业列表
  const getList = async () => {
    const obj = await getEnterpriseList({
      type: 1,
    });
    if (obj.list && Object.keys(obj.list).length) {
      setEnterprises(obj.list);
      setEnterpriseId(`${obj.id}`);
      await getPickSelf(obj.id);
    } else if (!enterpriseId) {
      notification.error({ message: '未找到企业' });
    }
    setPageLoaded(true);
  };

  useEffect(() => {
    getList();
  }, []);

  const options = {
    setVisibleSaleDate,
    setVisibleSaleSection,
    setVisiblePrice,
    setVisibleSort,
    onDel,
    setRecordID,
    setEditItem,
    enterpriseId,
    enterprises,
    onChangeEnterprise,
    onChangeFlag,
    onRefresh,
  };

  let request = () => ({
    data: [],
    total: 0,
  });
  if (enterpriseId) {
    request = params => searchList({ ...params });
  }

  return (
    <div className={utilStyle.formPageBox}>
      {pageLoaded && (
        <ProTable
          search={{
            span: 6,
            className: utilStyle.formSearch,
            collapsed: false,
            collapseRender: () => null,
          }}
          actionRef={refTable}
          tableClassName={utilStyle.formTable}
          columns={takeawayGoodsColumn(options)}
          request={request}
          rowKey={r => r.id}
          bordered
          options={false}
          form={{ initialValues: { enterpriseId } }}
          scroll={{ x: 1300 }}
          toolbar={{
            menu: {
              type: 'tab',
              activeKey,
              items: pickSelfList,
              onChange: key => {
                setActiveKey(`${key}`);
                onRefresh(true);
              },
            },
            actions: [
              <Button key="1" icon={<PlusOutlined />} type="primary" onClick={toAdd}>
                添加外卖商品
              </Button>,
            ],
          }}
        />
      )}
      {/* 可售日期弹窗 */}
      {visibleSaleDate && (
        <SaleDateModal
          visible={visibleSaleDate}
          id={recordID}
          item={editItem}
          type="saleDateList"
          handleRefresh={() => onRefresh()}
          handleClose={() => setVisibleSaleDate(false)}
        />
      )}
      {/* 可售餐段弹窗 */}
      {visibleSaleSection && (
        <SaleSectionModal
          visible={visibleSaleSection}
          id={recordID}
          enterpriseID={enterpriseId}
          type="tabCateList"
          item={editItem}
          handleRefresh={() => onRefresh()}
          handleClose={() => setVisibleSaleSection(false)}
        />
      )}
      {/* 修改企业商品价格弹窗 */}
      {visiblePrice && (
        <GoodPriceModal
          visible={visiblePrice}
          id={recordID}
          item={editItem}
          handleRefresh={() => onRefresh()}
          handleClose={() => setVisiblePrice(false)}
        />
      )}
      {/* 商品排序弹窗 */}
      {visibleSort && (
        <GoodSortModal
          visible={visibleSort}
          id={recordID}
          item={editItem}
          handleRefresh={() => onRefresh()}
          handleClose={() => setVisibleSort(false)}
        />
      )}
    </div>
  );
};

export default TakeawayGoods;
