/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-25 10:36:31
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */






import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { createFromIconfontCN } from '@ant-design/icons';

import { ActionType, arrayMoveImmutable, ProFormText, ProFormTextArea, useRefFunction } from '@ant-design/pro-components';
import ProForm, { ModalForm, ProFormCascader, ProFormCheckbox, ProFormDatePicker, ProFormDateRangePicker, ProFormDependency, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormSwitch } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Alert, Drawer, Form, Input, message, Popover, Radio } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';



import { editData, getTableDataReq } from './service';

import './style.less';

import { getDicDataBySysId } from '@/services/getDic';
import { authTimeType, KcimCenterSysId } from '@/constant';

import 'moment/locale/zh-cn';
import moment from 'moment';
import { sparse } from 'mathjs';
import AuthHisContent from './authHisttory';
import FormTabs from './tabs';
import { calculateDelayedDate } from '@/utils/tooljs';
import { debounce } from 'lodash';



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


const defaultExpiredDate = moment().startOf('days');

export default function QualificationExperiedMana() {
    const formRef = useRef<ProFormInstance>();
    const drawerFormRef = useRef<ProFormInstance>();
    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const [drawerVisible, set_drawerVisible] = useState(false);
    const [currentEditRow, set_currentEditRow] = useState<any>(undefined);
    const [currentPageTableData, set_currentPageTableData] = useState<any[]>([]);
    const [currentSelectedLeftRows, set_currentSelectedLeftRows] = useState<any[]>([]);
    const [currentSelectedTableRows, set_currentSelectedTableRows] = useState<any[]>([]);
    const [currentSelectedDrawerTableRows, set_currentSelectedDrawerTableRows] = useState<any[]>([]);

    const tableRef = useRef<ActionType>();
    const drawerTableRef = useRef<ActionType>();
    const [drawerTableData, set_drawerTableData] = useState<any[]>([]);
    const [modalFormVisible, set_modalFormVisible] = useState(false);
    const [operationLevel, set_operationLevel] = useState<any[]>([]);
    const [currentTab, set_currentTab] = useState<1 | 2>(1);


    const columns: ProColumns[] = [
        {
            title: '医生姓名',
            width: 80,
            ellipsis: true,
            renderText(text, record, index, action) {
                const { userInfo: { name } } = record;
                return name
            },
        },
        {
            title: '所在科室',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { userInfo: { deptName } } = record;
                return deptName
            },
        },
        {
            title: '资质名称',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { name } } = record;
                return name
            },
        },
        {
            title: '资质编码',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { code } } = record;
                return code
            },

        },
        {
            title: '资质分类',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { qualificationTypeName } } = record;
                return qualificationTypeName
            },

        },
        {
            title: '到期日期',
            ellipsis: true,
            dataIndex: 'endDate'

        },
        {
            title: '剩余天数',
            ellipsis: true,
            dataIndex: 'daysToExpire',

        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                return <a key={1} onClick={() => editExperiedHandle(record)}>调整期限</a>
            },
        },

    ];


    const getTableData = async (params: any) => {
        const { expireDate = defaultExpiredDate.format('YYYY-MM-DD') } = params;
        const resp = await getTableDataReq({ ...params, expireDate });
        if (resp) {
            const data = (resp.list).map((a: any, index: number) => ({ id: index, ...a }));
            set_currentPageTableData(data);
            return {
                data,
                success: true
            }
        } else {
            return []
        }
        // return {
        //     data: [
        //         {
        //             "id": 82,
        //             "qualificationCode": "djgfdcgrdsmdzcyk",
        //             "userId": 31241,
        //             "qualificationPeriod": 1,
        //             "applyDate": "2024-12-12 19:51",
        //             "applyMemo": "医务部批量授权",
        //             "beginDate": "2024-12-09",
        //             "endDate": "2024-12-31",
        //             "applyStatus": 5,
        //             "userInfo": {
        //                 "id": 31241,
        //                 "name": "赵海强",
        //                 "account": "010101",
        //                 "gender": "男",
        //                 "deptCode": "1282",
        //                 "deptName": "内镜门诊",
        //                 "title": "医师",
        //                 "jobTitle": "科主任",
        //                 "qualificationCertificateNo": "-",
        //                 "practiceCertificateNo": "-",
        //                 "doctorLevel": "执业医师",
        //                 "practiceCate": "临床",
        //                 "major": "内科专业",
        //                 "avatarUrl": ""
        //             },
        //             "qualificationInfo": {
        //                 "id": 4,
        //                 "code": "djgfdcgrdsmdzcyk",
        //                 "qualificationTypeCode": "erjiuzuu",
        //                 "qualificationTypeName": "二级手术",
        //                 "name": "单根导管冠脉造影术",
        //                 "standard": "依据",
        //                 "techFlag": 1,
        //                 "operationFlag": 1,
        //                 "operationLevelCode": "3",
        //                 "enableFlag": 1,
        //                 "allowCheck": 1
        //             },
        //             "currentStatus": "授权中",
        //             "daysToExpire": 18
        //         },
        //         {
        //             "id": 83,
        //             "qualificationCode": "a",
        //             "userId": 31240,
        //             "qualificationPeriod": 1,
        //             "applyDate": "2024-12-12 20:01",
        //             "beginDate": "2024-12-13",
        //             "endDate": "2025-01-31",
        //             "managerOpinion": "888",
        //             "applyStatus": 5,
        //             "userInfo": {
        //                 "id": 31240,
        //                 "name": "曾仁",
        //                 "account": "admin",
        //                 "gender": "男",
        //                 "deptCode": "1284",
        //                 "deptName": "便民门诊",
        //                 "title": "住院医师",
        //                 "jobTitle": "院长",
        //                 "qualificationCertificateNo": "SF230105198406020017",
        //                 "practiceCertificateNo": "N330182000001",
        //                 "doctorLevel": "执业医师",
        //                 "practiceCate": "临床",
        //                 "major": "内科专业",
        //                 "avatarUrl": "http://47.97.198.219:9000/center/20240711181142.jpg"
        //             },
        //             "qualificationInfo": {
        //                 "id": 6,
        //                 "code": "a",
        //                 "qualificationTypeCode": "BLUX",
        //                 "qualificationTypeName": "病历书写",
        //                 "name": "病历书写",
        //                 "standard": "斌彬彬",
        //                 "techFlag": 0,
        //                 "operationFlag": 1,
        //                 "operationLevelCode": "2",
        //                 "enableFlag": 1,
        //                 "allowCheck": 1
        //             },
        //             "currentStatus": "授权中",
        //             "daysToExpire": 49
        //         },
        //     ]
        // }
    }

    const editExperiedHandle = (record: any) => {
        set_currentEditRow(record);
        set_drawerVisible(true);
    }

    const getOperationLevelList = async () => {
        const resp = await getDicDataBySysId(KcimCenterSysId, 'SURGICAL_AND_OPERATIONAL_LEVELS');
        if (resp) {
            set_operationLevel(resp.dataVoList);
        }
    }


    const updateTable = async (formVal: any, type: 'EDIT_DRAWER' | 'EDIT') => {
        console.log({ formVal });
        try {

            let result: any[] = [];
            if (type == 'EDIT_DRAWER') {
                result = [{
                    qualificationApplyId: currentEditRow.id,
                    qualificationPeriod: currentEditRow.qualificationPeriod,
                    beginDate: currentEditRow.beginDate,
                    endDate: formVal.adjustType == 'days' ? calculateDelayedDate(currentEditRow.endDate, formVal.delayTime) : formVal.dateRange[1],
                    memo: formVal.memo
                }]
            }
            if (type == 'EDIT') {
                result = currentSelectedTableRows.map((a) => {
                    return {
                        qualificationApplyId: a.id,
                        qualificationPeriod: a.qualificationPeriod,
                        beginDate: a.beginDate,
                        endDate: formVal.adjustType == 'days' ? calculateDelayedDate(a.endDate, formVal.delayTime) : formVal.dateRange[1],
                        memo: formVal.memo
                    }
                })
            }

            const resp = await editData(result);
            if (resp) {
                set_currentSelectedTableRows([]);
                set_drawerVisible(false);


                tableRef.current?.reload();
                message.success('操作成功！');
            }

            return true;

        } catch (error) {

            console.log({ error });
            return false;
        }




    }


    const tableDataSearchHandle = (key: string) => {
        set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, [key]: tableDataSearchKeywords })
    }
    const getAuthPeriod = (code: number) => {
        const result = authTimeType.filter(a => a.value == code);
        return result.length > 0 ? result[0].label : '-'
    }

    useEffect(() => {
        if (drawerVisible) {
            getOperationLevelList();
        }
    }, [drawerVisible]);

    useEffect(() => {
        set_tableDataFilterParams({...tableDataFilterParams,expireDate:currentTab == 1?defaultExpiredDate.format('YYYY-MM-DD'):calculateDelayedDate(moment().startOf('day').format('YYYY-MM-DD'),0)})
    }, [currentTab])


    return (
        <KCIMPagecontainer className='QualificationExperiedMana' title={false}>
            <ModalForm
                title={'批量调整'}
                width={352}
                formRef={formRef}
                open={modalFormVisible}
                initialValues={{
                    adjustType: 'time',
                    dateRange: [moment().startOf('days'), moment().startOf('days')]
                }}

                onFinish={(val) => {
                    return updateTable({ ...val }, 'EDIT');
                }}
                modalProps={{ destroyOnClose: true, onCancel: () => set_modalFormVisible(false), }}
                colProps={{ span: 24 }}
                grid
                submitter={{
                    searchConfig: {
                        submitText: '调整',
                        resetText: '取消',
                    },
                }}
            >

                <Form.Item name="adjustType" >
                    <FormTabs width={188} />
                </Form.Item>
                <ProFormDependency name={['adjustType']}>
                    {
                        ({ adjustType }) => {
                            if (adjustType == 'time') {
                                return <ProFormDateRangePicker label='按授权时间：' name='dateRange' />
                            }
                            if (adjustType == 'days') {
                                return <ProFormDigit name='delayTime' width={80} label='延期天数：' />
                            }
                        }
                    }
                </ProFormDependency>

                <ProFormTextArea name={'memo'} fieldProps={{
                    style: { height: 85 }
                }} label='调整说明：' />

            </ModalForm>
            <Drawer destroyOnClose={true} className='QualificationExperiedMana-authDetailDrawer' width={700}
                open={drawerVisible} headerStyle={{ display: 'none' }} bodyStyle={{ background: '#F5F7FA', padding: 16 }}
            >
                <div className='authDetailDrawer-topBar'>
                    <div className='authDetailDrawer-topBar-title'>
                        <div className='closeIcon' onClick={() => set_drawerVisible(false)} ><IconFont  type={'iconquxiao'} /></div>{'批量授权'}
                    </div>
                    <div className='btnGroup'>
                        <span onClick={() => set_drawerVisible(false)}>取消</span>
                        {/* <span className='reject' onClick={() => updateTable(2)}>驳回</span> */}
                        <span className='commit' onClick={() => {
                            const val = drawerFormRef.current?.getFieldsFormatValue?.();
                            updateTable({ ...val }, 'EDIT_DRAWER')
                        }}>调整</span>
                    </div>
                </div>
                <div className='authDetailDrawer-content'>

                    <div className='authDetailDrawer-info'>
                        <div className='avator'><img src={(currentEditRow?.userInfo?.avatarUrl.length != 0) ? currentEditRow?.userInfo?.avatarUrl : require('../../../../static/avatar.png')} alt="avator" /></div>
                        <div className='authDetailDrawer-info-detail'>
                            <div className='authDetailDrawer-info-title'>
                                {currentEditRow?.userInfo?.name}
                                <img style={{ width: 16, height: 16, marginLeft: 8 }} src={require(`../../../../static/${currentEditRow?.userInfo?.gender == '男' ? 'male' : 'female'}.png`)} alt="" />
                            </div>
                            <div className='authDetailDrawer-info-title-sub'>
                                工号：{currentEditRow?.userInfo?.id}<span style={{ padding: '0 8px' }}></span>
                                科室：{currentEditRow?.userInfo?.deptName}<span style={{ padding: '0 8px' }}></span>
                                职称：{currentEditRow?.userInfo?.jobTitle}<span style={{ padding: '0 8px' }}></span>
                                职务：{currentEditRow?.userInfo?.title}
                            </div>
                        </div>

                    </div>
                    <div className='qualification-info'>
                        <div className='qualification-info-name'>
                            <div className='name'>{currentEditRow?.qualificationInfo.name}</div>
                            <div className='tags'>
                                {
                                    currentEditRow?.qualificationInfo.techFlag == 1 && (
                                        <span style={{
                                            display: 'inline-flex', width: 64, height: 20, justifyContent: 'center',
                                            alignItems: 'center', background: '#FFF5EB', borderRadius: 4, fontSize: 12, color: '#FF8000', marginRight: 4
                                        }}>医疗技术</span>
                                    )
                                }
                                {
                                    currentEditRow?.qualificationInfo.operationFlag == 1 && (
                                        <span style={{
                                            display: 'inline-flex', width: 64, height: 20, justifyContent: 'center',
                                            alignItems: 'center', background: '#E8FCF6', borderRadius: 4, fontSize: 12, color: '#009966'
                                        }}>{
                                                operationLevel.filter((a) => a.value == currentEditRow?.qualificationInfo.operationLevelCode).length > 0 ? (operationLevel.filter((a) => a.value == currentEditRow?.qualificationInfo.operationLevelCode))[0].name : <></>
                                            }</span>
                                    )
                                }

                            </div>
                        </div>
                        <div className='qualification-info-list'>资质分类：<span>{currentEditRow?.qualificationInfo.qualificationTypeName}</span></div>
                        <div className='qualification-info-list'>授权依据：<span>{currentEditRow?.qualificationInfo.standard}</span></div>
                        <div className='qualification-info-list'>授权期限：<span>{getAuthPeriod(currentEditRow?.qualificationPeriod ? currentEditRow?.qualificationPeriod : 1)}</span></div>
                        <div className='qualification-info-list'>授权时间：
                            <span>
                                {`${currentEditRow?.beginDate}至${currentEditRow?.endDate}`}
                                {currentEditRow?.applyAdjust?.length > 0 && (
                                    <Popover className='qualificationAuth-popover' overlayInnerStyle={{borderRadius:4}} content={<AuthHisContent hisList={[...currentEditRow?.applyAdjust]} />} title={false} >
                                        <IconFont type={'icon-qingliangtishi'} style={{ marginLeft: 10, cursor: 'pointer' }} />
                                    </Popover>
                                )}
                            </span>
                        </div>
                    </div>

                    <ProForm formRef={drawerFormRef} submitter={false} initialValues={{
                        adjustType: 'time',
                        // dateRange:[moment().startOf('days'),moment().startOf('days')]
                        dateRange: [moment(currentEditRow?.beginDate, 'YYYY-MM-DD'), moment(currentEditRow?.endDate, 'YYYY-MM-DD')],
                    }}>
                        <div className='authDetailDrawer-content-form'>
                            <div className='authDetailDrawer-content-form-title'>调整期限</div>
                            <div className='formWrapper'>
                                <Form.Item name="adjustType" >
                                    <FormTabs width={188} />
                                </Form.Item>
                                <ProFormDependency name={['adjustType']}>
                                    {
                                        ({ adjustType }) => {
                                            if (adjustType == 'time') {
                                                return <ProFormDateRangePicker name='dateRange' />
                                            }
                                            if (adjustType == 'days') {
                                                return <ProFormDigit name='delayTime' width={80} label='延期天数' />
                                            }
                                        }
                                    }
                                </ProFormDependency>

                                <ProFormTextArea name={'memo'} fieldProps={{
                                    style: { height: 85 }
                                }} label='调整说明：' />
                            </div>

                        </div>

                    </ProForm>
                </div>


            </Drawer>
            <div className='pageContent'>
                <div className='toolBar'>
                    <div className='filter'>
                        <div className='filterItem'>
                            <span className='label'>检索：</span>
                            <Input placeholder={'医生姓名、所在科室、资质分类、资质名称'} style={{ width: 330, marginRight: 16 }} allowClear autoComplete='off'

                                suffix={
                                    <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" onClick={() => tableDataSearchHandle('queryCondition')} />
                                }
                                onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                        set_tableDataSearchKeywords('');
                                        set_tableDataFilterParams({ ...tableDataFilterParams, queryCondition: null })
                                    }
                                }}

                                onPressEnter={(e) => {
                                    tableDataSearchHandle('queryCondition')
                                }}

                            />
                        </div>
                        <div className='tabSwitcher'>
                            <div className={currentTab == 1?'tab on':'tab'} onClick={() => set_currentTab(1)}>按日期</div>
                            <div className={currentTab == 2?'tab on':'tab'} onClick={() => set_currentTab(2)}>按天数</div>
                        </div>
                        {currentTab == 1 && <div className='filterItem'>
                            <span className='label'>到期时间：</span>
                            <ProFormDatePicker noStyle
                                allowClear
                                style={{ width: 160, marginRight: 16 }}
                                placeholder={'到期日期'}
                                fieldProps={{
                                    defaultValue: defaultExpiredDate,
                                    onChange(value, option) {
                                        set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, expireDate: value?.format('YYYY-MM-DD') })
                                    },
                                }}
                            />
                        </div>}

                        {
                            currentTab == 2 && <div className='filterItem'>
                                <span className='label' >剩余天数：</span>
                                <ProFormDigit noStyle
                                    width={120}
                                    allowClear
                                    placeholder={'365'}
                                    fieldProps={{
                                        onChange: debounce((value) => {
                                            set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, expireDate: calculateDelayedDate(moment().startOf('day').format('YYYY-MM-DD'), value ? value : 0) })
                                        }, 500),
                                    }}
                                />
                            </div>
                        }

                    </div>
                    {currentSelectedTableRows.length > 0 && (
                        <div className='btnGroup'>
                            <span className='batchAdjust' onClick={() => set_modalFormVisible(true)}>批量调整</span>
                        </div>
                    )}
                </div>
                <div style={{ marginTop: 16 }}>
                    <KCIMTable scroll={{ y: `calc(100vh - 230px)` }}
                        actionRef={tableRef} columns={columns as ProColumns[]} rowKey='id'
                        params={tableDataFilterParams}
                        request={(params) => getTableData(params)}
                        // dataSource={showList}
                        tableAlertRender={false}
                        rowSelection={{
                            selectedRowKeys: currentSelectedTableRows.map((a) => a.id),
                            onChange(selectedRowKeys, selectedRows, info) {
                                set_currentSelectedTableRows(selectedRows);
                            },
                        }}

                    />
                </div>
            </div>
        </KCIMPagecontainer>
    )
}
