/*
 * @Author: wufan
 * @Date: 2020-07-09 14:03:09
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-11-28 13:53:12
 * 店铺管理-员工管理
 */
import React, { useEffect, useState } from "react";
import { withRouter } from "react-router-dom";
import _ from "underscore";
import PageControl from "@/components/PageControl";
import { Button, Table,Modal,message} from "antd";
import { QuestionCircleOutlined } from '@ant-design/icons';
import StoreService from "@/domains/store-domain/storeService";
import CatalogAddOrEditModal from './modal/CatalogAddOrEditModal';
import SecondCatalogAddOrEditModal from './modal/SecondCatalogAddOrEditModal';
import "./CourseCatalogPage.less";
import User from '@/common/js/user';
const { confirm } = Modal;
interface RecordTypes {
  sonCategoryList: any;
}

function CourseCatalogPage() {
  const [courseCatalogList, setCourseCatalogList] = useState([]);
  const [size,setSize] =useState(10)
  const [query, setQuery] = useState({
    current: 0,
    storeId: User.getStoreId(),
  });
  
  const [total, setTotal] = useState(0);
  const [catalogModalVisible,setCatalogModalVisible] = useState(false);
  const [catalogModalType,setCatalogModalType] = useState('');
  const [secondCatalogModalVisible,setSecondCatalogModalVisible] = useState(false);
  const [secondCatalogModalType,setSecondCatalogModalType] = useState('');
  const [parentCatalogId,setParentCatalogId] = useState('');
  const [parentCatalogName,setParentCatalogName] = useState('');
  const [choosedItem, setChooseItem] = useState({});
  useEffect(() => {
    getCourseCatalogList();
  }, [query,size]);

  function addCatalog(){
    setChooseItem({});
    setCatalogModalVisible(true) ;
    setCatalogModalType('add');
  }
  function addSecondCatalog(record:any){
    setChooseItem({});
    setParentCatalogId(record.id);
    setParentCatalogName(record.categoryName);
    setSecondCatalogModalVisible(true);
    setSecondCatalogModalType('add');
  }
  function deleteCatalog(record:any){
    return  confirm({
      title: record.type==='parent'? '你确定要删除此分类吗？':'你确定要删除此子分类吗？',
      content: record.type==='parent'? '删除后，此分类下包含的所有子分类都会被删除，此操作不可恢复。':'此操作不可恢复。',
      icon: <span className="icon iconfont default-confirm-icon">&#xe839; </span>,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        handleDeleteCatalog(record);
      }
    })
  }

  function handleDeleteCatalog(record:any) {
    const param ={
      categoryId:record.id
    }
    StoreService.delCourseCategory(param).then((res: any) =>{
      getCourseCatalogList();
      message.success("分类已删除");
    });
  }
  function parseColumn():any{
    return [
        { title: '分类名称', 
          dataIndex: 'categoryName', 
          key: 'categoryName',
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width:300,
          render: (val: string, record: any) => {
            return (
              <div className="operation">
                  { record.type==="parent" && 
                    <>
                      <span
                        className="add-btn"
                        onClick={() => { addSecondCatalog(record) }}
                      >
                        添加子分类
                      </span>
                      <span className="divider-line">{" | "}</span>
                    </>
                  }
                 
                  <span className="edit-btn"
                    onClick={()=>{editCatalog(record)}}
                  >    
                  编辑
                  </span>
                  <span className="divider-line" >{" | "}</span>
                  <span  className="delete-btn" onClick={()=>{deleteCatalog(record)}}
                  >
                    删除
                  </span>
            </div>
            )

          },
        },
    ]
  }
  function getCourseCatalogList():any {
    console.log("query",query);
    let _query = _.clone(query);
    _query.current = query.current + 1;
    StoreService.getCourseCatalogList({..._query,size}).then((res: any) => {
      let resultData = handleCatalogListData(res.result.records)
      setCourseCatalogList(resultData);
      setTotal(res.result.total);
    });
  }

  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=_item.id
          return _item
        });
      }
      return item
    })
    return listData
  }

  function editCatalog(record:any){
    if(record.type ==="parent"){
      setCatalogModalType('edit');
      setCatalogModalVisible(true);
    }else{
      setParentCatalogId(record.parentId);
      setParentCatalogName(record.parentName);
      setSecondCatalogModalType('edit');
      setSecondCatalogModalVisible(true);
    }
    setChooseItem(record);
  }
  function onShowSizeChange(current:any, theSize:any) {
    setSize(theSize);
  }

  return (
    <div className=" page course-catalog-page">
        <div className="content-header">课程分类</div>
        <div className="box">
          <div className="box-header">
            <Button
              type="primary"
              className="add-show-btn"
              onClick={() => {addCatalog()}}
            >
              添加分类
            </Button>
          </div>
          <div className="box-body">
            <Table
                columns={ parseColumn() }
                pagination={false}
                expandedRowRender={(record:RecordTypes) => {
                  if(!record.sonCategoryList){
                    return <div className="empty-child">还未添加任何子分类</div>;
                  }
                  if (record.sonCategoryList.length !== 0){
                    return <Table columns={parseColumn()} dataSource={record.sonCategoryList} pagination={false}   className="child-table"/>
                  }else{
                    return <div className="empty-child">还未添加任何子分类</div>;
                  }
                }}
                dataSource={courseCatalogList}
                className="catalog-tabel"
            />
          </div>
          <div className="box-footer">
            <PageControl
               current={query.current}
               pageSize={size}
               total={total}
               showSizeChanger={true}
               onShowSizeChange={onShowSizeChange}
               toPage={(page: any) => {
                 const queryStates = _.clone(query);
                 queryStates.current = page;
                 setQuery(queryStates);
               }}
            />
          </div>
        </div>
        {
          catalogModalVisible && <CatalogAddOrEditModal modalType={catalogModalType} onClose={()=>{setCatalogModalVisible(false)}} refreshCatalogList={getCourseCatalogList} choosedItem={choosedItem}/>
        }
        {
          secondCatalogModalVisible && <SecondCatalogAddOrEditModal modalType={secondCatalogModalType} parentId={parentCatalogId} parentName={parentCatalogName} onClose={()=>{setSecondCatalogModalVisible(false)}} choosedItem={choosedItem} refreshCatalogList={getCourseCatalogList} />
        }
    </div>
  );
}

export default withRouter(CourseCatalogPage);
