/*
 * @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 {
  children: any;
}

function CourseCatalogPage() {
  const [courseCatalogList, setCourseCatalogList] = useState([]);

  const [query, setQuery] = useState({
    current: 0,
    size: 10,
    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 [choosedItem, setChooseItem] = useState({});
  useEffect(() => {
    getCourseCatalogList();
  }, [query]);
  function addCatalog(){
    setChooseItem({});
    setCatalogModalVisible(true) ;
    setCatalogModalType('add');
    
  }
  function addSecondCatalog(record:any){
    setChooseItem({});
    setParentCatalogId(record.id)
    setSecondCatalogModalVisible(true) ;
    setSecondCatalogModalType('add')
  }
  function deleteCatalog(record:any){
    return  confirm({
      title: record.type==='parent'? '你确定要删除此分类吗？':'你确定要删除此子分类吗？',
      content:  record.type==='parent' ? '删除后，此分类下包含的所有子分类都会被删除，此操作不可恢复。':'此操作不可恢复。',
      icon: <QuestionCircleOutlined />,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        handleDeleteCatalog(record.id);
      }
    })
  }

  function handleDeleteCatalog(categoryId: string) {
    const param ={
      categoryId
    }
    StoreService.delCourseCategory(param).then((res: any) =>{
      message.success("分类已删除");
      getCourseCatalogList();
    });
  }
  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"
                        onClick={() => { addSecondCatalog(record) }}
                      >
                        添加子分类
                      </span>
                      <span className="divider-line">{" | "}</span>
                    </>
                  }
                 
                  <span
                    onClick={()=>{editCatalog(record)}}
                  >    
                  编辑
                  </span>
                  <span className="divider-line" >{" | "}</span>
                  <span   onClick={()=>{deleteCatalog(record)}}
                  >
                    删除
                  </span>
            </div>
            )

          },
        },
    ]
  }
  function getCourseCatalogList():any {
    console.log('getCourseCatalogList')
    let _query = _.clone(query);
    _query.current = query.current + 1;
    StoreService.getCourseCatalogList(_query).then((res: any) => {
      let resultData = handleCatalogListData(res.result.records)
      setCourseCatalogList(resultData);
      console.log("res",resultData);
      setTotal(res.result.total);
    });
  }
  function handleCatalogListData(listData:any){
    listData.map((item:any,index:any) => {
      item.type = "parent"
      item.key = item.id;
      item.children = [];
      return item
    })
    
     return listData
  }

  function editCatalog(record:any){
   
    if(record.type ==="parent"){
      setCatalogModalType('edit');
      setCatalogModalVisible(true);
    }else{
      setSecondCatalogModalType('edit');
      setSecondCatalogModalVisible(true);
    }
    setChooseItem(record);
  }
  function expandSecondCatalog(expanded:boolean,record:any){
    const parentId = record.id;
    const param = {
      parentId,
    }
    StoreService.getAllSonCategory(param).then((res: any) => {
      record.children= res.result || [];
      record.children.map((item:any,index:any) => {
        item.key= item.id
        return item
      })
      const _courseCatalogList =[...courseCatalogList];
      console.log("_courseCatalogList",_courseCatalogList);
      setCourseCatalogList(_courseCatalogList)

    });
  }
  

  return (
    <div className=" page employee-manage-page">
      <div className="page-content">
        <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.children){
                    return
                  }
                  if (record.children.length === 0){
                    return <div>还未添加任何子分类</div>;
                  }
                }}
                dataSource={courseCatalogList}
                onExpand={(expanded, record)=>expandSecondCatalog(expanded, record)}
            />
          </div>
          <div className="box-footer">
            <PageControl
               current={query.current}
               pageSize={query.size}
               total={total}
               toPage={(page: any) => {
                 const queryStates = _.clone(query);
                 queryStates.current = page;
                 setQuery(queryStates);
               }}
              
            />
          </div>
        </div>
        {
          catalogModalVisible && <CatalogAddOrEditModal modalType={catalogModalType} onClose={()=>{setCatalogModalVisible(false)}} getCourseCatalogList={()=> getCourseCatalogList()} choosedItem={choosedItem}/>
        }
        {
          secondCatalogModalVisible && <SecondCatalogAddOrEditModal modalType={secondCatalogModalType} parentId={parentCatalogId} onClose={()=>{setSecondCatalogModalVisible(false)}} choosedItem={choosedItem} />
        }
      </div>
    </div>
  );
}

export default withRouter(CourseCatalogPage);
