/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-05-07 13:41:37
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-06-21 14:54:24
 * @FilePath: /BudgetManaSystem/src/pages/budgetMana/personnelSalaryBudget/components/cardList/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */



import { createFromIconfontCN } from '@ant-design/icons';
import { useEffect, useState } from 'react';
import { InputNumber,message,Modal } from 'antd'
import './style.less'
import { copyReq, getKpiRetainList, saveKpiRetain } from '../../service';


const IconFont = createFromIconfontCN({
    scriptUrl: '',
});

const formatValue = (value:number) => {
    if (value !== undefined && value !== null) {
      return parseFloat(value.toString().replace(/(\.\d*?[1-9])0+$/g, '$1').replace(/\.0*$/, ''));
    }
    return value;
};

function removeTrailingZeros(str:string) {
    // 将数字转换为字符串，并去掉多余的0
    return str.replace(/(\.\d*?[1-9])0+$/g, '$1').replace(/\.0*$/, '');
  }

export const CardList = ({ computeDate }: { computeDate: string }) => {

    const [listData, set_listData] = useState<any[]>([]);
    const [currentEdit, set_currentEdit] = useState<any>(undefined);
    const [currentEditGroup, set_currentEditGroup] = useState<any>(undefined);
    const [inputVal, set_inputVal] = useState(0);


    const editHandle = (group: any, current: any) => {
        if (currentEdit) {
            const newArr = listData.map((a) => {
                if (a.unitTypeCode === currentEditGroup.unitTypeCode) {
                    const newRetainList = a.retainList.map((b:any) => {
                        if (b.code === currentEdit.code) {
                            return { ...b, value: inputVal };
                        } else {
                            return b;
                        }
                    });
                    // 返回更新后的整个对象a，包括新的retainList和其他属性
                    return { ...a, retainList: newRetainList };
                } else {
                    return a;
                }
            });
          
            set_listData([...newArr]);
            savaData(newArr);
            set_currentEditGroup(undefined);
            set_currentEdit(undefined); return;
        } else {
            set_currentEdit({...current,flag:`${group.unitTypeCode}${current.code}`});
            set_currentEditGroup(group);
        }

    }

    const getData = async () => {
        const resp = await getKpiRetainList(computeDate);
        if (resp) {
            set_listData(resp);
        }
    }

    const onChangeHandle = (value: any) => {
        if (value !== undefined && value !== null) {
            // 将值转换为字符串并去掉无效的零
            const formattedValue = parseFloat(value.toString().replace(/(\.\d*?[1-9])0+$/g, '$1').replace(/\.0*$/, ''));
            set_inputVal(formattedValue);
          } else {
            set_inputVal(value);
          }
    }

    const savaData = async (newData:any)=>{
          const resp = await saveKpiRetain({
            computeDate,
            list:newData
          });
          if(resp){
                message.success('操作成功！');
          }
    }

    const copyReqHandle = async ()=>{
          Modal.confirm({
              title:'注意',
              content:'复制操作会覆盖已有的保留系数设定，确定要继续操作？',
              okText:'确定',
              cancelText:'取消',
              onOk:async (...args) => {
                const resp = await copyReq(computeDate);
                if(resp){
                  message.success('复制成功！');
                  getData();
                }
              },
          })
    }

    useEffect(() => {
        getData();
        // set_listData([
        //     {
        //         unitTypeName:'临床医生',
        //         retainList:[
        //             {
        //                 name:'季度考核',
        //                 value:1,
        //                 code:1
        //             },
        //             {
        //                 name:'季度考核',
        //                 value:1,
        //                 code:2
        //             }
        //         ]
        //     },
        //     {
        //         unitTypeName:'临床医生',
        //         retainList:[
        //             {
        //                 name:'季度考核',
        //                 value:1,
        //                 code:3
        //             },

        //         ]
        //     }
        // ])
    }, [])

    return (
        <div className="CardList">
            <div className="header">
                <span className="title">保留系数设定</span>
                <a className='copyBtn' onClick={()=>copyReqHandle()}> <IconFont style={{ color: '#3377FF', paddingRight: 4,fontSize:16 }} type="iconfuzhi1" />复制上月</a>
            </div>
            <div className='content'>
                {
                    listData.map((a, index) => (
                        <div className='group' key={index}>
                            <div className='groupName'>{a.unitTypeName}</div>
                            <div className='listWrap'>
                                {
                                    a.retainList.map((b: any, i: number) => (
                                        <div className='list' key={i}>
                                            <div className='name'>
                                                <img src={require(`../../../../../../static/${b.type == 1 ? 'textImg_xi.png' : 'textImg_zhi.png'}`)} alt="" />
                                                {b.name}
                                            </div>
                                            <div className='detail'>
                                                {currentEdit?.flag != `${a.unitTypeCode}${b.code}` && <span className='num'>{b.type == 1?(removeTrailingZeros((b.value * 100).toFixed(4))+'%'):removeTrailingZeros((b.value).toFixed(2))}</span>}
                                                {currentEdit?.flag == `${a.unitTypeCode}${b.code}` && <InputNumber precision={b.type == 1 ? 4 : 2} min={0} max={b.type == 1?1:10000000000} style={{ width: 160 }} autoFocus defaultValue={formatValue(b.value)} onChange={onChangeHandle} />}
                                                <div className='actIcon'><IconFont style={{ color: '#17181A', cursor: 'pointer' }} onClick={() => editHandle(a, b)} type={currentEdit?.flag != `${a.unitTypeCode}${b.code}` ? 'icon-xiugai' : 'icon-queren'} /></div>
                                            </div>
                                        </div>
                                    ))
                                }
                            </div>
                        </div>
                    ))
                }
            </div>
        </div>
    )


}