/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:46:46
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-15 16:19:53
 * @Description: 描述一下
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React, { useState, useRef, useEffect } from 'react';
import { Table, Modal, message , Tooltip,Switch,Dropdown} from 'antd';
import { withRouter } from 'react-router-dom';
import { PageControl } from "@/components";
import PlanService from "@/domains/plan-domain/planService";
import SharePlanModal from '../modal/SharePlanModal';
import {LIVE_SHARE} from '@/domains/course-domain/constants';
import User from '@/common/js/user';
import './PlanList.less';

const { confirm } = Modal;
const userRole =  User.getUserRole();
function PlanList(props) {
    const [sharePlanModal, setSharePlanModal] = useState(null);
   
    function parseColumns(){
        const columns = [
            {
                title: '培训计划',
                key: 'planName',
                dataIndex: 'planName',
                width:'18%',
                render: (val, record) => {
                    return (
                        <div className="plan-name">
                            {val}
                        </div>
                    )
                }
            },
            {
                title: '课程总数量',
                key: 'courseNum',
                dataIndex: 'courseNum',
                width: '10%',
                render: (val, record) => {
                return (
                    <div className="course-number">
                        {val}
                    </div>
                )
                }
            },
            {
                title: '当前状态',
                width: '10%',
                dataIndex: "status",
                render: (val, item, index) => {
                    return  (
                        <Switch  checked={item.enableState==="NO"?false:true}  onChange={()=>changeEnableState(item)} disabled={(User.getUserRole() === "CloudManager" || User.getUserRole() === "StoreManager")?false:true}/>
                    ) 
                },
            },
            {
                title: '创建人',
                key: 'createName',
                dataIndex: 'createName',
                width: '10%',
                render: (val) => {
                return (
                    <div className="create-name">
                        {val}
                    </div>
                )
                }
            },
            {
                title: '创建时间',
                width: "12.5%",
                key: 'created',
                dataIndex: 'created',
                sorter: true,
                render: (val) => {
                return  formatDate('YYYY-MM-DD H:i', val) 
                }
            },
            {
                title: '更新时间',
                width: "10%",
                key: 'updated',
                dataIndex: 'updated',
                sorter: true,
                render: (val) => {
                return formatDate('YYYY-MM-DD H:i', val) 
                }
            },
            {
                title: '参培人数',
                width:76,
                key: 'cultureCustomerNum',
                dataIndex: 'cultureCustomerNum',
                sorter: true,
                render: (val) => {
                    return ( 
                        <div className="join-number">
                            {val}
                        </div>
                    ) 
                }
            },
            {
                title: '操作',
                key: 'operate',
                dataIndex: 'operate',
                fixed: 'right',
                width: 176,
                render: (val, record) => {
                    return (
                        <div className="operate">
                            <div className="operate__item" onClick={()=>toLearningDataPage(record)}>学习数据</div>
                            {record.enableState==="YES" &&
                                <>
                                    <span className="operate__item split"> | </span>
                                    <div className="operate__item" onClick={() => {handleShowShareModal(record); }}>分享</div>
                                </>
                            }
                            {(User.getUserRole() === "CloudManager" || User.getUserRole() === "StoreManager") &&
                                <>
                                <span className="operate__item split"> | </span>
                                <Dropdown overlay={renderMoreOperate(record)}>
                                    <span className="more-operate">
                                    <span className="operate-text">更多</span>
                                    <span
                                        className="iconfont icon"
                                        style={{ color: "#5289FA" }}
                                    >
                                        &#xe824;
                                    </span>
                                    </span>
                                </Dropdown>
                                </>
                            }
                        </div>
                    )
                }
            }
        ];
        return columns;
    }
    
    function renderMoreOperate(item){
        return (
            <div className="live-course-more-menu">
                
                <div  className="operate__item"
                onClick={()=>toEditPlanPage(item)}
                >编辑</div>
                <div
                className="operate__item" onClick={()=>handleDelete(item)}
                >删除</div>
            </div>
        )
    }
    
    function handleChangeTable(pagination, filters, sorter){
        const { columnKey, order } = sorter;
        const { query } = props;
        let  _columnKey;
        let _order;

        // 按创建时间升序排序
        if (columnKey === 'created' && order === 'ascend') {_columnKey="CREATED"; _order = 'SORT_ASC'; }
        // 按创建时间降序排序
        if (columnKey === 'created' && order === 'descend') { _columnKey="CREATED"; _order = 'SORT_DESC';}
        // 按更新时间升序排序
        if (columnKey === 'updated' && order === 'ascend') { _columnKey="UPDATED"; _order = 'SORT_ASC'; }
        // 按更新时间降序排序
        if (columnKey === 'updated' && order === 'descend') { _columnKey="UPDATED"; _order = 'SORT_DESC'; }
        // 按更新时间升序排序
        if (columnKey === 'cultureCustomerNum' && order === 'ascend') { _columnKey="CUSTOMER_NUM"; _order = 'SORT_ASC'; }
        // 按更新时间降序排序
        if (columnKey === 'cultureCustomerNum' && order === 'descend') { _columnKey="CUSTOMER_NUM"; _order = 'SORT_DESC'; }
        const _query = {
          ...query,
          sortMap:{}
        };
        _query.sortMap[_columnKey]=_order;
        props.onChange(_query);
    }
        // 显示分享弹窗
    function handleShowShareModal(item) {
        const htmlUrl = `${LIVE_SHARE}training_plan_detail/${item.planId}?id=${User.getStoreId()}&storeUserId=${User.getStoreUserId()}`;
        const longUrl = htmlUrl
        const shareData = { ...item, longUrl };
        const sharePlanModal = (
            <SharePlanModal
                data={shareData}
                type="liveClass"
                close={() => {
                    setSharePlanModal(null)
                   
                }}
            />
        )
        setSharePlanModal(sharePlanModal)
    }
     //改变上架状态
    function changeEnableState(item){
      let _enableState = item.enableState
      if(_enableState==='NO'){
        _enableState = "YES";
        item.enableState = "YES"
      }else{
        _enableState = "NO"
        item.enableState = "NO"
      }
      const params={
        "planId": item.planId,
        "enableState":_enableState
      }
      PlanService.updateStateTrainingPlan(params).then((res)=>{
        if(res.success){
          if(_enableState === "YES"){
            message.success("已启用此计划");
          }else{
            message.success("已禁用此计划");
          }
          props.onChange();
        }
      }) 
    } 
    
    function toEditPlanPage(item){
        window.RCHistory.push({
            pathname: `/create-plan?type=edit&id=${item.planId}`,
        })
    }
    function toLearningDataPage(item){
        window.RCHistory.push({
            pathname: `/learning-data?id=${item.planId}`,
        })
    }
    function handleDelete(record){
      return  confirm({
        title: '你确定要删除吗？',
        content: '删除后，此培训计划的用户将无法继续学习，所有学习数据将同步删除不可恢复',
        icon: <span className="icon iconfont default-confirm-icon">&#xe839; </span>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        width:440,
        height:188,
        onOk: () => {
          if(record.enableState === "YES"){
              Modal.warning({
                  title: '无法删除',
                  content: '培训计划启用中，无法直接删除',
              });
          }else{
              deleteConfirm(record);
          }
          
        }
      })
    }
    function deleteConfirm(item){
      const params={
          "planId": item.planId,
      }
      PlanService.deleteTrainingPlan(params).then((res)=>{
        if(res.success){
            message.success("删除成功");
            props.onChange();
        }
      }) 
    }
    function onShowSizeChange(current, size){
        if (current === size) {
            return
        }
        let _query = props.query
        _query.size = size;
        props.onChange(_query)
    }
    return (
        <div className="plan-list">
            <Table
                rowKey={record => record.id}
                showSorterTooltip={false}
                dataSource={props.planListData}
                columns={ parseColumns() }
                pagination={false}
                onChange={handleChangeTable}
                bordered
                size="middle"
                scroll={{ x: 1400}}
                className="plan-list-table"
            />
            <div className="box-footer">
                <PageControl
                    current={props.query.current - 1}
                    pageSize={props.query.size}
                    total={props.totalCount}
                    toPage={(page) => {
                        const _query = {...props.query, current: page + 1};
                        props.onChange(_query)
                    }}
                    onShowSizeChange={onShowSizeChange}
                />
            </div>  
            {sharePlanModal }
        </div>
    )
  }
  
  export default withRouter(PlanList);