/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-11-08 16:42:54
 * @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 { formatMoneyNumber } from '@/utils/format';
import { createFromIconfontCN } from '@ant-design/icons';
import FormItem from 'antd/es/form/FormItem';

import { ActionType, ProFormDateTimePicker, ProFormInstance, ProFormText } from '@ant-design/pro-components';
import { ModalForm, ProFormDependency, ProFormDigit, ProFormRadio, ProFormSelect, ProFormSwitch } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Form } from 'antd';
import { useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';



import { addData, delData, editData, getDrugTableData, importDataPost } from './service';

import './style.less';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq } from '@/utils/tooljs';



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



export default function MaterialCostManagement() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [stopStat,set_stopStat] = useState(0);

    const columns: ProColumns[] = [

        {
            title: '项目代码',
            dataIndex: 'code',
        },
        {
            title: '项目名称',
            dataIndex: 'name',
        },
        {
            title: '项目类型',
            dataIndex: 'type',
            renderText(num) {
                return num == 1?'不计价材料':'高值材料'
            },
        },
        {
            title: '单价',
            dataIndex: 'price',
            renderText(num) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '成本',
            dataIndex: 'cost',
            renderText(num) {
                return formatMoneyNumber(num)
            },
        },
        {
            title: '停用',
            dataIndex: 'status',
            renderText(stat) {
                return stat ? '是' : '否'
            },
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        const resp = await getDrugTableData({...params,stop:stopStat});
        if (resp) {
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        return []
    }

    const delTableData = async (record: any) => {
        const resp = await delData(record.id);
        if (resp) {
            message.success('操作成功！');
            tableRef.current?.reload();
            // message.success('操作成功!');
        }
    }

    const updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {

        const result = {
            ...formVal
        }

        if (type == 'ADD') {
            const resp = await addData(result);
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }

        }
        if (type == 'EDIT') {

            const resp = await editData({ ...result });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        return true;

    }


    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' }) => {

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}药品`}
                width={350}
                formRef={formRef}
                initialValues={type == 'EDIT' ? {
                    ...record,
                } : { status: 0 }}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormText
                    name="code"
                    label="项目代码："
                    placeholder="请输入"
                    rules={[{ required: true, message: '项目代码不能为空!' }]}
                />
                <ProFormText
                    name="name"
                    label="项目名称："
                    placeholder="请输入"
                    rules={[{ required: true, message: '项目名称不能为空!' }]}
                />
                <ProFormSelect
                    name="type"
                    label="项目类型："
                    placeholder="请选择"
                    options={[
                        {
                            label: '不计价材料',
                            value: 1
                        },
                        {
                            label: '高值材料',
                            value: 2
                        }
                    ]}
                    rules={[{ required: true, message: '项目类型不能为空!' }]}
                />
                <ProFormDigit
                    name="price"
                    label="单价："
                    placeholder="请输入"
                    rules={[{ required: true, message: '单价不能为空!' }]}
                />
                <ProFormDigit
                    name="cost"
                    label="成本："
                    placeholder="请输入"
                    rules={[{ required: true, message: '成本不能为空!' }]}
                />
                <Form.Item style={{ width: 322 }} label={<span style={{}}><i style={{ fontSize: 14, color: '#FF4060', fontWeight: 400, position: 'relative', paddingRight: 4, paddingLeft: 4 }}>*</i>停用：</span>}>
                    <div style={{ display: 'flex', flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                        <ProFormRadio.Group
                            name="status"
                            noStyle
                            colProps={{ span: 10 }}
                            options={[
                                {
                                    label: '否',
                                    value: 0
                                },
                                {
                                    label: '是',
                                    value: 1
                                }
                            ]}
                        />
                        {/* style={{position:'relative',left:-10}}  */}
                        <ProFormDependency name={['status']}>
                            {
                                ({ status }) => {
                                    // console.log({report});
                                    return (

                                        status ? <ProFormDateTimePicker fieldProps={{ locale }} name="stopTime" colProps={{ span: 14 }} rules={[{ required: true, message: '时间不能为空!' }]} noStyle /> : null
                                    )
                                }
                            }
                        </ProFormDependency>

                    </div>
                </Form.Item>


            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {

        set_tableDataFilterParams({
            ...tableDataFilterParams,
            [`${paramName}`]: tableDataSearchKeywords
        })

    }

    const downloadTemplate = async () => {
        await downloadTemplateReq('/costAccount/setting/exportMaterial');
    };

    const importData = () => {
        return (
            <ModalForm
                width={360}
                title={`导入数据`}
                trigger={
                    <a className="import" key="3">
                        导入
                    </a>
                }
                submitter={{
                    render: (props, defaultDoms) => {
                        const needBtn = defaultDoms.filter((b) => {
                            return b.key != 'rest';
                        });
                        return [
                            // <Button
                            //     key="ok"
                            //     onClick={auditType == '0' ? () => downloadTemplate(index) : () => { }}
                            // >
                            //     下载模板
                            // </Button>,
                            ...needBtn,
                        ];
                    },
                }}
                onFinish={async (values) => {
                    const {
                        importFile: { fileList },
                    } = values;

                    let formData = new FormData();
                    formData.append('file', fileList[0].originFileObj);
                    const resp = await importDataPost(formData);

                    if (resp) {
                        tableRef.current?.reload();
                        return true;
                    }
                }}
            >
                <FormItem name={'importFile'}>
                    <KCIMUpload downloadTemplateFile={() => downloadTemplate()} />
                </FormItem>
            </ModalForm>
        );
    };


    useEffect(() => {

    }, [])

    return (
        <KCIMPagecontainer className='MaterialCostManagement' title={false}>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem' style={{marginRight:16}} >
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 项目类型：</span>
                        <ProFormSelect noStyle placeholder={'请选择类型'}
                            width={160}
                            options={[
                                {label:'不计价材料',value:1},
                                {label:'高值材料',value:2}
                            ]}
                            fieldProps={{
                                onChange(value, option) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        itemType: value
                                    });
                                },
                            }}
                        />
                    </div>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 项目名称：</span>
                        <Input placeholder={'请输入'} allowClear
                            suffix={
                                <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('name')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        name: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

                                set_tableDataFilterParams({
                                    ...tableDataFilterParams,
                                    name: (e.target as HTMLInputElement).value
                                });
                            }}

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    <span style={{ paddingRight: 16 }}><ProFormSwitch noStyle fieldProps={{ size: 'small', onChange: (bool) => {
                         set_stopStat(bool ? 1 : 0);
                         tableRef.current?.reload();
                     } }} /> 显示停用项目</span>
                    {importData()}
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>

            <div style={{ marginTop: 16 }}>
                <KCIMTable columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </KCIMPagecontainer>
    )
}
