/*
 * @Author: your name
 * @Date: 2021-09-10 11:44:42
 * @LastEditTime: 2021-10-09 15:09:56
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /MedicalWisdomCheckSys/src/pages/GradeHospitalAccreditation/accreditationDetail/components/FormList/index.tsx
 */



import React, { useState, useEffect,useContext, ChangeEvent,forwardRef,useImperativeHandle } from 'react'
import { Button, Image,Input } from 'antd';
import { ProFormSelect } from '@ant-design/pro-form';
import {
    CloseCircleOutlined
  } from '@ant-design/icons';
import './index.less'


const { TextArea } = Input;

const FormList = forwardRef<FormList.FormListRefCurrent,FormList.FormListProps>((props,ref) => {

    const [data, setData] = useState<FormList.MapList[]>([]);
    const {formContext} = props;
    const providerData = useContext<MccsModal.MccsModalContextT>(formContext);
    const {data:formListData,selecterList=[]} = props;
    // console.log({props,providerData});


    const formHandle = (type: string,supKey: number|string) => {
        const tempData = data;
        if(type=='add'){
            const newFormObj: FormList.MapList = {
                key:new Date().getTime(),
                evaluation:'',
                list: [
                    {
                        key:new Date().getTime(),
                        detail:''
                    }
                ]
            }
    
            tempData.push(newFormObj);
        }
        if(type=='del'){
            
            tempData.splice(tempData.findIndex(item=>item.key == supKey),1)
        }

        setData([...tempData]);
        
    }

    const textAreaHandle = (type: string,supKey: number|string,subKey?: number|string) => {
        // console.log({type,supKey,subKey});
        const tempData = data;
        const needUpdateItem = (tempData.filter(item=>item.key == supKey ))[0];

        if(type=='add'){
            const newObj = {key:new Date().getTime(),detail:''};

            needUpdateItem?.list?.push(newObj);

            setData([...tempData]);

        }
        if(type=='del'){
            needUpdateItem.list.splice(needUpdateItem.list.findIndex(item=>item.key==subKey),1);
            setData([...tempData]);
            // setInputVal('',supKey,subKey);
        }
    }

    
    const setInputVal = (val: any,supKey: string|number,subKey?: string|number)=>{
        //  console.log(val.target.value,supKey,subKey);
         const copiedData = data;
         const currentGroup = (copiedData.filter(item=>item.key==supKey))[0]; // 选出父级

         if(subKey||subKey==0){
             // 单个修改
            const currentChildInputTextArea = (currentGroup.list.filter(val=>val.key ==subKey ))[0]; // 选出子集

            if(typeof val === 'object'){
               // 来自ChangeEvent时
               currentChildInputTextArea.detail = val?.target.value;
            }else {
               currentChildInputTextArea.detail = val;
            }
         }else {
             // 批量删除
             currentGroup.list.forEach((val,i)=>{
                val.detail = ''
             });
         }
        
         setData([...copiedData]);
    }


    const selecterChangeHandle = (value: any,index: number)=>{
        //  console.log({value});
         const copiedData = data;
         copiedData[index].evaluation = value;
    }


    useEffect(() => {
        const { data = [] } = props;
        const _data = data.map((item,index)=>{
              const {detail:list,evaluation} = item;
              const tempList = list.map((val: any,i: number)=>({key:i,detail:val.title}));
              return {
                   key:index,
                   evaluation,
                   list:tempList
              }
        });
        // console.log({_data});
        setData(_data);
    }, [formListData]);


    useImperativeHandle(ref,()=>{
        // getData 就是暴露给父组件的方法
        const getData = ()=>{
            return data;
        }
        return {getData}
    });

    return (
        <div className='formListContainer'>
            <div className='content'>

                {
                    data?.map((item, index) => {
                        return (

                            <div className='formList' key={index}>
                                <span className='formListCloseBtn'>
                                    <Image width={15} preview={false} onClick={() =>formHandle('del',item.key)} src={'https://i.postimg.cc/HLkhvpBL/image.png'} />
                                </span>
                                <ProFormSelect
                                    options={selecterList}
                                    fieldProps={{
                                        onChange:val=>selecterChangeHandle(val,index)
                                    }}
                                    initialValue={item.evaluation}
                                    width="md"
                                    name={`score-${index}-${item.key}`}
                                    label={`评分`}
                                />
                                <div className='listWrap'>
                                    {
                                        item.list?.map((val, i) => {
                                            return (
                                                <div className='textAreaList' key={i}>
                                                    <div className='label'>{`细则${i+1}:`}</div>
                                                    <TextArea  style={{width:'80%'}} value={val.detail} maxLength={100} allowClear onChange={e=>setInputVal(e,item.key,val.key)} placeholder='请输入' />
                                                    <span  className='ProFormTextAreaCloseBtn' onClick={()=>textAreaHandle('del',item.key,val.key)}>
                                                        <CloseCircleOutlined />
                                                    </span>
                                                </div>
                                            )
                                        })
                                    }
                                    <Button onClick={() => textAreaHandle('add',item.key)}>新增</Button>
                                </div>

                            </div>
                        )
                    })
                }

            </div>
            <Button type="primary" onClick={()=>formHandle('add',0)}>新增</Button>
        </div>
    )
})



export default FormList;


