import React, { useState, useEffect } from "react"
import { Card, Select, Row, Col, Input, Divider, Tabs, Table, Button, Modal, Form, Popover, message, Popconfirm, Image, Badge } from "antd"
import { CloseOutlined, LinkOutlined, PlusOutlined, UploadOutlined } from "@ant-design/icons"
import { history, connect } from "umi"
import classNames from 'classnames';
import utilsStyles from '@/utils/utils.less';

import UploadFile from '@/components/ImgUploadFile'
import useFormTable from '@/useHooks/useFormTable'
import { dispatchHandle } from '@/utils/publicHandle'
import EditableTable from "../components/EditableTable"
import { isImg } from '../utils/util'
import style from "./index.less"
import ToolTipsBox from "@/components/ToolTipsBox";
import AddFeeModal from '../components/AddFeeModal'

const { Option } = Select
const { TextArea } = Input
const { Meta } = Card;
const { TabPane } = Tabs

const AddNote = (props) => {
    const {
        dispatch,
        feeLoading,
        location: {
            query
        },
        maintaining: {
            tasksDetail,
            taskDetailOutFeeList,
            firmList
        }
    } = props;
    const [feevisible, setFeeVisible] = useState(false) //对话框显示隐藏
    const [outSourcingList, setOutSourcingList] = useState([])
    const [form] = Form.useForm()
    const [feeForm] = Form.useForm()
    // 费用列表
    const getFeeListItem = (payload = {}) => {
        payload.taskId = query.id
        dispatchHandle(
            dispatch,
            'maintaining/operation_service_m_curing_task_expensesPageList_post',
            payload,
            res => {
                setOutSourcingList(res)
            }
        )
    }
    const { tableProps: feeTableProps, search: feeSearch } = useFormTable(getFeeListItem, {
        form: feeForm
    })
    // 表格行的选择
    const [selectedRowKeys, setSelectedRowKeys] = useState([])// 选中的行的key值
    const rowSelections = {
        selectedRowKeys,
        onChange: (selectedRowKey, selectedRows) => {
            console.log('标准selectedRowKeys changed: ', selectedRowKey, selectedRows);
            setSelectedRowKeys(selectedRowKey);
        },
        fixed: true
    };
    const deleteRequest = (payload = []) => {
        dispatchHandle(
            dispatch,
            'maintaining/operation_service_m_curing_task_expensesDelete_patch',
            payload,
            () => {
                feeSearch.refresh()
            }
        )
    }
    // 费用表格编辑
    const [editId, setEditId] = useState()
    const [type, setType] = useState('add')
    const editFeeAction = (record) => {
        setEditId(record.id)
        setType('edit')
        setFeeVisible(true)
    }
    // 费用表格单行删除
    const deleteFeeConfirm = (record) => {
        deleteRequest([record.id])
    }
    // 是否委外养护
    const [isOutSourcing, setIsOutSourcing] = useState(false)
    const isOutSourcingChange = (value) => {
        setIsOutSourcing(value)
    }
    // 费用删除事件
    const [deleteFeeVisible, setDeleteFeeVisible] = useState(false)
    const [deleteFeeLoading, setDeleteFeeLoading] = useState(false)
    const feeDeleteAction = () => {
        if (selectedRowKeys.length === 0) {
            message.warn('请选择要删除的费用!')
        } else {
            setDeleteFeeVisible(true)
        }
    }
    // 多项删除
    const deleteFeeOk = () => {
        setDeleteFeeLoading(true);
        deleteRequest(selectedRowKeys)
        setDeleteFeeVisible(false)
    }
    // 文件上传
    const [imgList, setImgList] = useState([]);
    const [fileList, setfileList] = useState();
    // upload
    const changeUpload = (files, fileInfo) => {
        console.log(files, fileInfo);
        const value = String(files);
        const filesList = fileInfo.fileList;
        setImgList(filesList);
        setfileList(value)
    }
    // 费用对话框事件方法
    const feeShowModal = () => {
        setFeeVisible(true)
        setType('add')
    };
    // 删除附件事件
    // // 附件删除
    const deleteAnnexAction = (id, index) => {
        const arr = imgList.filter(i => id !== i.uid)
        setImgList(arr)
        message.success('删除成功!')
    }
    const deleteImgAction = (id, index) => {
        const arr = imgList.filter(i => id !== i.uid)
        setImgList(arr)
        message.success('删除成功!')
    }
    const checkAnnexAction = (url) => {
        dispatchHandle(
            dispatch,
            'maintaining/account_service_file_online_preview_url_post',
            { name: url },
            res => {
                if (res) {
                    window.open(res)
                }
            }
        )
    }
    // 点击确定按钮
    const addNoteChange = (e) => {
        e.preventDefault();
        form.validateFields()
            .then((values) => {
                console.log(values, tasksDetail, `=======`)
                const arr = imgList.length > 0 && imgList.map(item => ({
                    enclosurName: item.name,
                    url: item.response.data.url || ''
                }))
                const obj = {
                    outsourcingOrNot: values.outsourcingOrNot || tasksDetail.outsourcingOrNot,
                    appointedUnit: values.appointedUnit || tasksDetail.appointedUnit,
                    estimatedCost: values.estimatedCost || tasksDetail.estimatedCost,
                    acceptancePerson: values.acceptancePerson || tasksDetail.acceptancePerson,
                    maintenanceRecord: values.maintenanceRecord || tasksDetail.maintenanceRecord,
                    delegationInstructions: values.delegationInstructions || tasksDetail.delegationInstructions,
                }
                const payload = {
                    ...obj,
                    taskId: query.id,
                }
                if (values?.outsourcingOrNot) {
                    payload.enclosurs = arr || []
                }
                dispatchHandle(
                    dispatch,
                    'maintaining/operation_service_m_curing_task_addTaskRecord_post',
                    payload
                )
                form.resetFields();
                history.goBack();
            })
            .catch((err) => {
                console.log('Validate Failed:', err);
            });
    }
    useEffect(() => {
        dispatchHandle(
            dispatch,
            'maintaining/operation_service_m_curing_task_detail_id_get',
            { id: query.id },
            res => {
                if (res) {
                    form.setFieldsValue(res)
                    setIsOutSourcing(res.outsourcingOrNot)
                    if (res.taskEnclosurs && res.taskEnclosurs.length > 0) {
                        const urlArr = res.taskEnclosurs?.map(item => ({
                            uid: item?.id,
                            name: item.enclosurName,
                            response: {
                                data: {
                                    url: item?.url
                                }
                            }
                        }))
                        console.log(urlArr , res.taskEnclosurs)
                        setImgList(urlArr)
                    }

                }
            }
        )
        dispatchHandle(
            dispatch,
            'maintaining/common_service_m_maintenance_manufacturer_pageList_post',
            {}
        )
    }, [])
    const columns = [
        {
            title: '费用类型',
            dataIndex: 'usageTypeName',
        },
        {
            title: '单位',
            dataIndex: 'companyName',
        },
        {
            title: '需求数量',
            dataIndex: 'demandQuantity',
            editable: true
        },
        {
            title: '单价(元)',
            dataIndex: 'unitPrice',
            editable: true
        },
        {
            title: '小计',
            dataIndex: 'specs',
            render: (text, record) => <a>{(record.demandQuantity * record.unitPrice) || 0}</a>
        },
        {
            title: '使用人',
            dataIndex: 'nameOfUser',
        },
        {
            title: '费用说明',
            dataIndex: 'costDescription',
            render: (text) => <a>{text}</a>
        },
        {
            title: '附件',
            dataIndex: 'annex',
            render: (text, record) => <ul style={{ display: 'flex', flexWrap: "wrap", flexDirection: 'column', alignItems: 'flex-start' }}>
                {
                    record.expenseso && record.expenseso.length > 0 &&
                    record.expenseso.map((item, index) => (
                        <li key={index} style={{ marginRight: 10, display: 'flex', alignItems: 'center' }}>
                            <LinkOutlined style={{ color: 'rgba(0,0,0,0.45)', paddingRight: 5 }} />
                            <ToolTipsBox>
                                <span>{item?.enclosurName || ''}</span>
                            </ToolTipsBox>
                        </li>
                    ))
                }
            </ul>
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (text, record, index) => <div>
                <a onClick={() => editFeeAction(record)}>编辑</a>
                <Divider type="vertical" />
                <Popconfirm
                    title="确认删除此费用?"
                    onConfirm={() => deleteFeeConfirm(record)}
                >
                    <a>移除</a>
                </Popconfirm>
            </div>
        }

    ];
    return <Card className={style.add_note}>
        <h3 className={style.h3_title}>养护信息:</h3>
        <Form form={form}>
            <Row className={style.add_note_head} gutter={[{ md: 8, xxl: 16 }]}>
                <Col span={8}>
                    <i>是否委外养护</i>
                    <Form.Item name="outsourcingOrNot" style={{ marginBottom: 0, flex: 1 }}>
                        <Select onChange={isOutSourcingChange} placeholder="请选择" allowClear>
                            <Option value>是</Option>
                            <Option value={false}>否</Option>
                        </Select>
                    </Form.Item>
                </Col>
                {
                    isOutSourcing && (
                        <>
                            <Col span={8}>
                                <i>委派单位</i>
                                <Form.Item name="appointedUnit" style={{ marginBottom: 0, flex: 1 }}>
                                    <Select
                                        placeholder="请选择"
                                        allowClear
                                        showSearch
                                        optionFilterProp="children"
                                    >
                                        {firmList?.length > 0 && firmList?.map(item => <Option value={item?.id}>{item?.name}</Option>)}
                                    </Select>
                                </Form.Item>
                                <span className={style.isRequired}>*</span>
                            </Col>
                            <Col span={8}>
                                <i>预计费用</i>
                                <Form.Item name="estimatedCost" style={{ marginBottom: 0, flex: 1 }}>
                                    <Input placeholder="请输入" allowClear />
                                </Form.Item>
                                <span className={style.unit}>元</span>
                            </Col>
                        </>
                    )
                }
            </Row>
            <Row className={style.main_note} justify="space-between">
                <Col span={isOutSourcing ? 12 : 24}>
                    <h4>养护记录:</h4>
                    <Form.Item name="maintenanceRecord">
                        <TextArea rows="5" placeholder="请输入" allowClear />
                    </Form.Item>
                </Col>
                {
                    isOutSourcing ? <Col span={12}>
                        <h4>委外说明:</h4>
                        <Form.Item name="delegationInstructions">
                            <TextArea rows="5" placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col> : null
                }
            </Row>
            {/* 附件 */}
            <div className={style.main_annex} style={{ marginBottom: 50 }}>
                <h4>附件:</h4>
                <Row gutter={[8, 16]}>
                    <Col span={18}>
                        <Card
                            bordered
                            // className={style.annex_content}
                            title={
                                <div style={{ width: '100%', display: 'flex', flexWrap: 'wrap' }}>
                                    {

                                        imgList && imgList.length > 0 &&
                                        imgList.filter(item => {
                                            if (item?.name && isImg(item?.name?.substr(item?.name.lastIndexOf('.') + 1))) {
                                                return item
                                            }
                                        }).map((item, index) => (
                                            <div style={{ marginBottom: 16, marginRight: 16 }} key={item.uid}>
                                                <Badge offset={[-3, 0]} count={<CloseOutlined onClick={() => deleteImgAction(item?.uid, index)} style={{ color: '#fff', background: '#ff0000', borderRadius: '50%' }} />}>
                                                    <Image
                                                        style={{ width: 100, height: 100, margin: '0 10px 10px 0', cursor: 'pointer' }}
                                                        alt=""
                                                        key={item.uid}
                                                        src={item?.response?.data?.url || '/pageImg/defaultImg@2x.png'}
                                                        fallback="/pageImg/defaultImg@2x.png"
                                                    />
                                                </Badge>
                                            </div>
                                        ))
                                    }
                                </div>
                            }
                        >
                            {
                                imgList && imgList.length > 0 &&
                                imgList.filter(item => {
                                    if (item?.name && !isImg(item?.name?.substr(item?.name.lastIndexOf('.') + 1))) {
                                        return item
                                    }
                                }).map((item, index) => (
                                    <div style={{ display: 'flex', margin: '0 16px 5px 0' }}>
                                        <Meta
                                            // onClick={() => checkAnnexAction(item?.response?.data?.url)}
                                            key={index}
                                            description={item.name || ''}
                                            avatar={<LinkOutlined style={{ marginRight: 5 }} />}
                                            style={{ marginRight: 5, marginBottom: 5, cursor: 'pointer' }}
                                        />
                                        <CloseOutlined style={{ fontSize: 12 }} onClick={() => deleteAnnexAction(item?.uid, index)} />
                                    </div>
                                ))
                            }
                        </Card>
                    </Col>
                    <Col span={6} style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                        <Form.Item name="annex">
                            <UploadFile
                                fileType="document"
                                onChange={changeUpload}
                                showUploadList={false}
                            >
                                <Button style={{ color: 'rgba(0,0,0,0.65)' }}><UploadOutlined />上传文档</Button>
                            </UploadFile>
                        </Form.Item>
                        <i style={{ color: 'rgba(0,0,0,0.65)' }}>支持扩展名:.rar .zip .doc .docx .pdf .png...</i>
                    </Col>
                </Row>
            </div>
        </Form>
        {
            isOutSourcing ? <div className={style.main_fee}>
                <h3 className={style.h3_title}>养护费用</h3>
                <Divider />
                <Tabs defaultActiveKey="1">
                    <TabPane tab="委外费用" key="1">
                        <div className={style.out_buttons}>
                            <Button icon={<PlusOutlined />} type="primary" onClick={feeShowModal}>添加费用</Button>
                            <Button danger onClick={feeDeleteAction}>删除</Button>
                            <Modal
                                title='删除费用提醒'
                                visible={deleteFeeVisible}
                                confirmLoading={deleteFeeLoading}
                                onOk={deleteFeeOk}
                                onCancel={() => setDeleteFeeVisible(false)}
                            >
                                确认删除选中的费用?
                            </Modal>
                        </div>
                        <EditableTable
                            loading={feeLoading}
                            rowSelection={rowSelections}
                            optColumns={columns}
                            tableData={outSourcingList}
                            setTableData={setOutSourcingList}
                            pagination={taskDetailOutFeeList.pagination}
                            tableProps={feeTableProps}
                        />
                    </TabPane>
                </Tabs>
            </div> : null
        }
        <div style={{ position: 'fixed', right: 20, bottom: 20 }}>
            <Button style={{ marginRight: "16px" }} onClick={() => history.goBack()}>取消</Button>
            <Button onClick={addNoteChange} type="primary">保存</Button>
        </div>
        <AddFeeModal
            feevisible={feevisible}
            setFeeVisible={setFeeVisible}
            id={query.id}
            editId={editId}
            type={type}
            search={feeSearch}
        />
    </Card>
}

export default connect(({ maintaining, dict, loading }) => ({
    dict,
    maintaining,
    feeLoading: loading.effects['maintaining/operation_service_m_curing_task_expensesPageList_post']
}))(AddNote)