import React, { useState, useEffect } from 'react';
import {
  Card,
  List,
  Drawer,
  Button,
  Empty,
  Spin,
  notification,
  Switch,
  message,
} from 'antd';
import {
  modifyProduct,
  getProductList,
  delProductList,
} from '@/services/webConfig/api';
import classnames from 'classnames';
import AddForm from './components/productForm';
import EditForm from './components/editForm';
import styles from './productConfig.less';
const ProductConfig = props => {
  const [addVisible, setAddVisible] = useState(false);
  const [productList, setProductList] = useState([]);
  const [userProductsList, setUserProductsList] = useState([]);
  const [productObj, setProductObt] = useState(null);
  const [loading, setLoading] = useState(false);
  const [flag, setFlag] = useState(1);
  useEffect(() => {
    setLoading(true);
    getProductList()
      .then(res => {
        const { code } = res;
        if (code === 0) {
          const {
            data: { AllProducts, UserProducts },
          } = res;
          setProductList(AllProducts);
          setUserProductsList(UserProducts);
          // if (!productObj && data.length > 0) {
          //   setProductObt(data[0]);
          // }
          // setProductList(data);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, [flag]);
  // 展示新增抽屉
  const handleAdd = () => {
    setAddVisible(true);
  };
  // 删除
  const handleDel = item => {
    setLoading(true);
    delProductList({ ...item })
      .then(res => {
        setLoading(false);
        if (res.code === 0) {
          notification.success({
            message: '提示',
            description: '关闭成功',
            duration: 3,
          });
          setProductObt('');
          setFlag(flag + 1);
        } else {
          notification.error({
            message: '提示',
            description: res.msg || '关闭失败',
            duration: 10,
          });
        }
      })
      .catch(err => {
        setLoading(false);
        console.error(err);
      });
  };
  // 新增提交回调
  const addCallback = val => {
    setAddVisible(false);
    setFlag(flag + 1);
  };
  // 编辑的回调
  const editCallback = val => {
    setLoading(true);
    modifyProduct(val)
      .then(res => {
        setLoading(false);
        if (res.code === 0) {
          notification.success({
            message: '提示',
            description: '编辑成功',
            duration: 3,
          });
          setFlag(flag + 1);
        } else {
          notification.error({
            message: '提示',
            description: res.msg || '编辑失败',
            duration: 10,
          });
        }
      })
      .catch(err => {
        setLoading(false);
        console.log(err);
      });
  };
  const handleSwitchClick = (e, item, userlist) => {
    if (e) {
      setLoading(true);
      modifyProduct({ ...item })
        .then(res => {
          setLoading(false);
          if (res.code === 0) {
            notification.success({
              message: '提示',
              description: '启用成功',
              duration: 3,
            });
            setFlag(flag + 1);
          } else {
            notification.error({
              message: '提示',
              description: res.msg || '启用失败',
              duration: 10,
            });
          }
        })
        .catch(err => {
          setLoading(false);
          console.log(err);
        });
    }
    if (!e) {
      let obj = userlist.find(i => i.PackageName === item.PackageName);
      handleDel(obj);
    }
  };
  const handleClickItem = value => {
    if (userProductsList.length > 0) {
      let obj = userProductsList.find(i => i.PackageName === value.PackageName);
      if (obj) {
        setProductObt(obj);
      } else {
        message.warning({
          content: '请先启用产品',
          duration: 3,
        });
      }
    } else {
      message.warning({
        content: '请先启用产品',
        duration: 3,
      });
    }
  };
  const renderListItem = arr =>
    arr.map(item => (
      <List.Item
        key={item.PackageName}
        className={classnames({
          [styles.listItem]: true,
          [styles.selected]: item.PackageName === productObj?.PackageName,
        })}
        onClick={() => handleClickItem(item)}
      >
        <div onClick={e => e.stopPropagation()}>
          <Switch
            // size="small"
            // defaultChecked={item.IsUsed}
            checked={item.IsUsed}
            checkedChildren="启用"
            unCheckedChildren="关闭"
            onClick={e => {
              handleSwitchClick(e, item, userProductsList);
            }}
          />
        </div>
        <span className={classnames({ [styles.itemspan]: true })}>
          {item.ProductName}
        </span>
      </List.Item>
    ));
  return (
    <Spin spinning={loading} tip="loading...">
      <div className={styles.box}>
        <Card className={classnames(`${styles.leftList}`)}>
          <div className={styles.listTop}>
            产品选择：
            {/* <Button type="primary" onClick={handleAdd}>
              新增
            </Button> */}
            {/* <Button type="primary" danger onClick={handleDel}>
              删除
            </Button> */}
          </div>
          {productList && productList.length > 0 ? (
            <List>{renderListItem(productList)}</List>
          ) : (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="暂无数据"
            />
          )}
        </Card>
        <Card className={styles.rightForm}>
          {productList && productList.length > 0 && productObj ? (
            <EditForm
              productObj={productObj}
              editCallback={editCallback}
              handleDel={handleDel}
            />
          ) : (
            <Empty
              style={{ marginTop: '60px' }}
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="当前未选中产品类型"
            />
          )}
          {/* <Drawer
            title="新增产品"
            destroyOnClose
            maskClosable={false}
            width={600}
            onClose={() => {
              setAddVisible(false);
            }}
            visible={addVisible}
          >
            <AddForm addCallback={addCallback} />
          </Drawer> */}
        </Card>
      </div>
    </Spin>
  );
};
export default ProductConfig;
