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, apiMealInfoDel, apiMealInfoUpdate } from './service';
import { getEnterpriseList, getShopList } 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 [pageLoading, setPageLoading] = useState(true); // 可售日期弹窗
  const [visibleSaleDate, setVisibleSaleDate] = useState(false); // 可售日期弹窗
  const [visibleSaleSection, setVisibleSaleSection] = useState(false); // 可售餐段弹窗
  const [visiblePrice, setVisiblePrice] = useState(false); // 修改企业商品价格弹窗
  const [visibleSort, setVisibleSort] = useState(false); // 商品排序弹窗
  const [enterprises, setEnterprises] = useState({ 1: { text: '领红包' } }); // 企业列表
  const [shopEnum, setShopEnum] = useState({}); // 店铺列表
  const [activeKey, setActiveKey] = useState('');
  const [enterpriseId, setEnterpriseId] = useState('1');
  const [pickSelfList, setPickSelfList] = useState([]); // 取餐点列表
  const [recordID, setRecordID] = useState(''); // 编辑的记录ID

  // 搜索商品列表
  const searchList = async params => {
    if (params.enterpriseId && params.enterpriseId !== enterpriseId) {
      setEnterpriseId(params.enterpriseId);
    }
    const data = {
      page: params.current,
      size: params.pageSize,
      data: Object.assign(
        {
          enterpriseId,
        },
        params,
      ),
    };
    const res = await apiTakeawayList(data);
    return {
      data: res.records,
      total: res.total,
    };
  };
  const onDel = async id => {
    await apiMealInfoDel({
      id,
    });
    notification.success({
      message: '删除成功',
    });
  };
  const onAdd = async () => {
    const query = getToUrlQuery();
    history.push({
      pathname: '/takeawayGoodsInfo',
      query,
    });
  };

  const onChangeFlag = async (id, checked) => {
    const params = {
      id,
      showFlag: checked ? 1 : 0,
    };
    await apiMealInfoUpdate(params);
    notification.success({ message: '保存成功' });
  };

  // 根据企业ID获取取餐点
  const getPickSelf = async id => {
    const res = await apiSelPickSelfList({ enterpriseId: id });
    if (res) {
      setPickSelfList(
        res.map(item => ({
          key: item.pickSelfId,
          label: <span>{item.pickSelfName}</span>,
        })),
      );
      setActiveKey(res[0].pickSelfId);
    }
  };

  // 根据企业ID获取取餐点
  // const getShops = async () => {
  //   const res = await getShopList({});
  //   setShopEnum(res.list);
  // };

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

  // 获取企业列表
  const getList = async () => {
    const obj = await getEnterpriseList();
    if (obj.list && Object.keys(obj.list).length) {
      setEnterprises(obj.list);
      setEnterpriseId(obj.id);
      getPickSelf(obj.id);
      setPageLoading(true);
    }
  };

  useEffect(() => {
    getList();
    // getShops();
    // setTimeout(() => {
    //   // refTable.current.reload();
    // }, 1000);
  }, []);

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

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

export default TakeawayGoods;
