import React, { useState, useEffect } from 'react';
import { Card, List, Empty, Spin, notification, Switch, Button } from 'antd';
import {
  modifyProduct,
  getProductList,
  delProductList,
  ProductRepair,
} from '@/services/webConfig/api';
import classnames from 'classnames';
import { ToolOutlined } from '@ant-design/icons';

import EditForm from './components/editForm';
import styles from './productConfig.less';
const ProductConfig = props => {
  const [productList, setProductList] = useState([]);
  const [userProductsList, setUserProductsList] = useState([]);
  const [productObj, setProductObj] = useState('');
  const [loading, setLoading] = useState(false);
  const [flag, setFlag] = useState(1);
  const [list, setList] = useState(new Set());
  const [keepData, setKeepData] = useState(false);
  // 默认展示第一项
  // useEffect(() => {
  //   setLoading(true);
  //   getProductList()
  //     .then(res => {
  //       const { code } = res;
  //       if (code === 0) {
  //         const {
  //           data: { AllProducts, UserProducts },
  //         } = res;
  //         // setProductList(AllProducts);
  //         setUserProductsList(UserProducts);
  //         setProductObj(AllProducts[0]);
  //         AllProducts.map(i => {
  //           list.add(i.ProductType);
  //         });
  //         let a = [];
  //         list.map(i => {
  //           a.push(i);
  //         });
  //         let aa = [];
  //         a.map((i, j) => {
  //           let ad = [];
  //           AllProducts.map(k => {
  //             if (k.ProductType == i) {
  //               ad.push(k);
  //             }
  //           });
  //           aa.push(ad);
  //         });
  //         setProductList(aa);
  //       }
  //     })
  //     .finally(() => {
  //       setLoading(false);
  //     });
  // }, []);

  useEffect(() => {
    setLoading(true);
    getProductList()
      .then(res => {
        const { code } = res;
        if (code === 0) {
          const {
            data: { AllProducts, UserProducts },
          } = res;
          // setProductList(AllProducts);
          setKeepData(res.data.IsAuthorize);
          setUserProductsList(UserProducts);
          if (!productObj && AllProducts.length > 0) {
            setProductObj(AllProducts[0]);
          }
          // setProductList(data);
          AllProducts.map(i => {
            list.add(i.ProductType);
          });
          let a = [];
          [...list].map(i => {
            a.push(i);
          });
          let aa = [];
          a.map((i, j) => {
            let ad = [];
            AllProducts.map(k => {
              if (k.ProductType == i) {
                ad.push(k);
              }
            });
            aa.push(ad);
          });
          setProductList(aa);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, [flag]);

  // 删除
  const handleDel = item => {
    setLoading(true);
    delProductList({ ...item })
      .then(res => {
        setLoading(false);
        if (res.code === 0) {
          item.IsUsed = false;
          setProductObj(item);
          notification.success({
            message: '提示',
            description: '关闭成功',
            duration: 3,
          });
          setFlag(flag + 1);
        } else {
          notification.error({
            message: '提示',
            description: res.msg || '关闭失败',
            duration: 10,
          });
        }
      })
      .catch(err => {
        setLoading(false);
        console.error(err);
      });
  };

  // 编辑的回调
  const editCallback = val => {
    setLoading(true);
    modifyProduct(val)
      .then(res => {
        setLoading(false);
        if (res.code === 0) {
          setFlag(flag + 1);
          notification.success({
            message: '提示',
            description: '编辑成功',
            duration: 3,
          });
        } else {
          notification.error({
            message: '提示',
            description: res.msg || '编辑失败',
            duration: 10,
          });
        }
      })
      .catch(err => {
        setLoading(false);
        console.log(err);
      });
  };
  const handleSwitchClick = (e, item, userlist) => {
    console.log(userlist);
    if (e) {
      setLoading(true);
      modifyProduct({ ...item })
        .then(res => {
          setLoading(false);
          if (res.code === 0) {
            setFlag(flag + 1);
            notification.success({
              message: '提示',
              description: '启用成功',
              duration: 3,
            });
            item.IsUsed = true;
            setProductObj({ ...item });
          } 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 => {
    console.log(value);
    setProductObj({ ...value });
  };

  const renderListItem = arr => (
    <div style={{ marginBottom: '25px', borderBottom: '1px solid #ccc', paddingBottom: '25px' }}>
      {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
              checked={item.IsUsed}
              disabled={keepData ? true : false}
              checkedChildren="启用"
              unCheckedChildren="关闭"
              onClick={e => {
                handleSwitchClick(e, item, userProductsList);
              }}
            />
          </div>
          <span className={classnames({ [styles.itemspan]: true })}>
            {item.ProductType ? `${item.ProductName}【${item.ProductType}】` : item.ProductName}
          </span>
        </List.Item>
      ))}
    </div>
  );

  const repair = () => {
    setLoading(true);
    ProductRepair().then(res => {
      setLoading(false);
      if (res.code === 0) {
        setFlag(flag + 1);
        notification.success({
          message: '提示',
          description: '修复成功',
          duration: 3,
        });
      } else {
        notification.error({
          message: '提示',
          description: res.msg,
          duration: 3,
        });
      }
    });
  };
  return (
    <Spin spinning={loading} tip="loading...">
      <div className={styles.box}>
        <Card className={classnames(`${styles.leftList}`)}>
          <div className={styles.listTop}>
            <div>可用产品：</div>
            <Button
              onClick={() => {
                repair();
              }}
            >
              <ToolOutlined />
              修复授权
            </Button>
          </div>
          <div style={{ height: 'calc(100% - 50px)', overflow: 'scroll' }}>
            {productList && productList.length > 0 ? (
              productList.map(item => renderListItem(item))
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
            )}
          </div>
        </Card>
        <Card className={styles.rightForm}>
          <EditForm
            productObj={productObj}
            editCallback={editCallback}
            handleDel={handleDel}
            userProductsList={userProductsList}
          />
        </Card>
      </div>
    </Spin>
  );
};
export default ProductConfig;
