import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Card, Button, notification } from 'antd';
import EditableTag from '@/components/EditableTag';
import { getDishList } from '@/services/api/dish';
import { getPackageList, getPackageDetailList } from '@/services/api/package';
import {
  updateGuaranteeTask,
  getGuaranteeDetailList,
  addGuaranteeDetailBatch,
  deleteGuaranteeDetail
} from '@/services/api/guaranteeTask';
import Selector from './components/Selector';

export default (props) => {
  const { dataSource, setDataSource } = props;

  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(false);
  const packageRef = useRef();

  const handlePackageSubmit = ({item, amount}) => {
    packageRef.current = item;

    // 获取套餐下所有的菜肴
    // 然后把菜肴放入到列表
    getPackageDetailList({ pageNum: 1, pageSize: 500, packageId: item.id }).then(res => {
      const { records = [] } = res;
      if (records.length > 0) {
        for (let it of records) {
          const found = list.filter(x => x.dishId === it.id)[0]
          if (found) {
            found.dishAmount = amount;
          } else {
            list.push({
              guaranteeId: dataSource.id,
              dishId: it.id,
              dishName: it.name,
              dishUnit: it.unit,
              dishAmount: amount,
            })
          }
        }

        setList(list.slice());
      }
    })
  };

  const handleDishSubmit = ({item, amount}) => {
    const found = list.filter(x => x.dishId === item.id)[0]
    if (found) {
      found.dishAmount = amount;
    } else {
      list.push({
        guaranteeId: dataSource.id,
        dishId: item.id,
        dishName: item.name,
        dishUnit: item.unit,
        dishAmount: amount,
      })
    }

    setList(list.slice());
  };

  const onDelete = (item) => {
    if (item.id) {
      setLoading(true);
      deleteGuaranteeDetail(item.id).then(res => {
        setLoading(false);

        const nwList = list.filter(x => x.dishId !== item.dishId);
        setList(nwList);
      }).catch(() => {
        setLoading(false);
      })
    } else {
      const nwList = list.filter(x => x.dishId !== item.dishId);
      setList(nwList);
    }
  }

  const onSubmit = () => {
    setLoading(true);
    addGuaranteeDetailBatch(list, dataSource.id).then(res => {
      setLoading(false);
      setList(res);
      notification.success({ message: '操作成功' });
    }).catch(() => {
      setLoading(false);
    });

    if (packageRef.current) {
      dataSource.packageName = packageRef.current.name;
      updateGuaranteeTask(dataSource, dataSource.id).then(res => {
        setDataSource(res);
      });
    }
  }

  useEffect(() => {
    if (dataSource && dataSource.id) {
      setLoading(true);
      getGuaranteeDetailList({ pageNum: 1, pageSize: 500, guaranteeId: dataSource.id }).then(res => {
        setLoading(false);
        setList(res.records || []);
      }).catch(() => {
        setLoading(false);
      })
    }
  }, [dataSource])

  return (
    <Row gutter={48}>
      <Col span={8}>
        <div>
          <h3>选择套餐</h3>
          <Selector
            placeholder="请选择套餐"
            disabled={!dataSource}
            fetch={getPackageList}
            onSubmit={handlePackageSubmit}
          />
        </div>
        <div style={{ marginTop: '48px' }}>
          <h3>选择菜肴</h3>
          <Selector
            placeholder="请选择菜肴"
            disabled={!dataSource}
            fetch={getDishList}
            onSubmit={handleDishSubmit}
          />
        </div>
      </Col>
      <Col span={16}>
        <Card
          title="已选菜肴"
          loading={loading}
          extra={<Button disabled={!dataSource} type='primary' loading={loading} onClick={onSubmit}>保存</Button>}
        >
          <EditableTag
            list={list}
            keyFuc={x => x.dishId}
            labelFunc={x => `${x.dishName} × ${x.dishAmount}`}
            onDelete={onDelete}
          />
        </Card>
      </Col>
    </Row>
  )
}
