/*
 * @Author: wufan
 * @Date: 2020-11-27 16:21:49
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-02-01 14:02:30
 * @Description: Description
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React, { useState, useEffect } from "react";
import { Modal,Form,Input,Button,Select,message} from "antd";
import './SecondCatalogAddOrEditModal.less'
import User from '@/common/js/user';
import _ from "underscore";
import StoreService from "@/domains/store-domain/storeService";


const { Option } = Select;
interface SecondCatalogAddOrEditModalProps {
  onClose:any;
  modalType:string;
  parentId:string;
  choosedItem:any;
  refreshCatalogList:any;
  parentName:string
}

function SecondCatalogAddOrEditModal(props: SecondCatalogAddOrEditModalProps) {
  const {onClose,modalType,parentId,refreshCatalogList,choosedItem,parentName} = props;
  console.log('choosedItem',choosedItem);
  const [secondCatalogName,setSecondCatalogName] =  useState(choosedItem.categoryName);
  const [selectParentId,setSelectParentId] =  useState(parentId);
  const [optionList,setOptionList] = useState([]);
  const [hasNext,setHasNext] = useState(false);
  const [clickStatus,setClickStatus] = useState(false);
  const [query, setQuery] = useState({
    current: 0,
    size:10,
    storeId: User.getStoreId(),
  });

  useEffect(() => {
    getOptionList();
  },[query]);

  function handleScroll(e:any){
    const container = e.target;
    const scrollToBottom = container &&  container.scrollHeight <= container.clientHeight + container.scrollTop;
    if (scrollToBottom && hasNext) {
      let _query = _.clone(query);
      _query.current = query.current + 1;
      setQuery(_query);
    }
  }
  function getOptionList():any {
    let _query = _.clone(query);
    _query.current = query.current + 1;
    StoreService.getCourseCatalogList(_query).then((res: any) => {
      let resultData = handleCatalogListData(res.result.records);
      let listData:any = [...optionList,...resultData]
      setHasNext(res.result.hasNext);
      setOptionList(listData);
    });
  }
  function handleCatalogListData(listData:any){
    listData.map((item:any,index:any) => {
      item.type = "parent"
      item.key = item.id;
      if(item.sonCategoryList){
        item.sonCategoryList.map((_item:any,_index:any) =>{
          _item.type = "child";
          _item.key="child" + _item.id 
          return _item
        });
      }
      return item
    })
    return listData
  }

  function handleConfirm(){
    if (clickStatus) {
      return;
    }
    setClickStatus(true);
    setTimeout(() => {
      setClickStatus(false);
    }, 1000);
    
    if(modalType === "add"){
      addSecondcatalog();
    }else{
      editSecondcatalog();
    }
  }
  function addSecondcatalog():any{
    const param = {
      parentId:selectParentId,
      storeId: User.getStoreId(),
      categoryName:secondCatalogName
    }
    StoreService.addCourseCategory(param).then((res: any) => {
      refreshCatalogList();
      onClose();
      message.success("添加子分类成功");
    });
  }
  function editSecondcatalog():any{
    const param = {
      parentId:selectParentId,
      categoryId:choosedItem.id,
      categoryName: secondCatalogName,
    }
    StoreService.editCourseCategory(param).then((res: any) => {
      refreshCatalogList();
      onClose();
      message.success("编辑子分类成功");
    });
  }
  return (
    <Modal
      visible={true}
      title={modalType === "add" ? '添加子分类' : '编辑子分类' }
      className="second-catalog-add-edit-modal"
      onCancel={onClose}
      width={448}
      footer={[
        <Button
            id='cancel_allot_btn'
            key="back" onClick={onClose}>取消</Button>,
        <Button
            id='confirm_allot_btn'
            key="submit"
            type="primary"
            onClick={() => {
                handleConfirm()
            }}>
            保存
        </Button>
      ]}
      maskClosable={false}
      closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
    >
     <Form
        labelCol={ {span:6 }}
     >
        <Form.Item
              label="子分类名称"
              name="子分类名称"
              rules={[{ required: true}]}
          >
          <Input type="text" 
              placeholder="请输入子分类名称，最多10个字"
              maxLength={10}  
              style={{ width: 240 }}  
              defaultValue={secondCatalogName}
              autoComplete="off"
              onChange={(e) => { 
                setSecondCatalogName(e.target.value);
              }}  
          />  
        </Form.Item>
        <Form.Item
              label="所属分类"
              name="所属分类"
              rules={[{ required: true}]}
          >
           <Select
                style={{ width: 240 }}
                defaultValue={parentName}
                onPopupScroll={handleScroll}
                suffixIcon={<span className="icon iconfont" style={{fontSize:'12px',color:'#BFBFBF'}}>&#xe835;</span>}
                onChange={(value) => {
                  setSelectParentId(String(value))
                }}
                
              >
                {_.map(optionList, (item:any, index) => {
                  return <Option id={item.id} value={item.id}>{item.categoryName}</Option>
                })}

              </Select>
        </Form.Item>
     </Form>
    </Modal>
  );
}

export default SecondCatalogAddOrEditModal;
