import React, { useState, useEffect } from 'react'
import {
    ValidatorForm,
    TextValidator,
    SelectValidator,
} from 'react-material-ui-form-validator'
import {
    Button,
    Grid,
    MenuItem,
    Typography,
    IconButton,
    Icon,
    Tooltip,
} from '@material-ui/core'
import _ from 'lodash'
import {
    createGasStation,
    detailGasStation,
    deleteGasField,
    deleteGasOnline,
} from 'app/apis/Functions/merchant'
import { showLoading, hideLoading } from 'app/redux/actions/loadingAction'
import { toast } from 'react-toastify'
import { Breadcrumb, SimpleCard } from 'app/components'
import { Link, useHistory, useLocation } from 'react-router-dom'
import { trimObject } from 'app/config/Function'
import { connect } from 'react-redux'
import { dropdownMerchant } from 'app/apis/Functions/dropdown'
import Table from '@material-ui/core/Table'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableContainer from '@material-ui/core/TableContainer'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import Paper from '@material-ui/core/Paper'
import CreateField from 'app/components/dialog/CreateField'
import CreateFountain from 'app/components/dialog/CreateFountain'
import UpdateFountain from 'app/components/dialog/UpdateFountain'
import { useTranslation } from 'react-i18next'

const SimpleForm = (props) => {
    const [state, setState] = useState({})
    const history = useHistory()
    const [listDrop, setListDrop] = useState([])
    const [openCreate, setOpenCreate] = useState(false)
    const [listField, setListField] = useState([])
    const [fountainSelected, setFountainSelected] = useState()
    const [openUpdate, setOpenUpdate] = useState()
    const location = useLocation()
    const { t } = useTranslation()
    useEffect(() => {
        getDateDetail()
        getData()
    }, [])

    const getDateDetail = async () => {
        props.showLoading()
        const res = await detailGasStation(location.state, {})
        props.hideLoading()
        if (res.data.code == 200 && res.data.data) {
            console.log(res.data.data.gas_fields)
            if (res.data.data.gas_fields) {
                setListField(res.data.data?.gas_fields)
            }

            setState(res.data.data)
        } else if (res.data.code == 401) {
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const getData = async () => {
        props.showLoading()
        const res = await dropdownMerchant({})
        props.hideLoading()
        if (res.data.code == 200 && res.data.data) {
            const newList = res.data.data.map((e) => {
                return { ...e, name: e.merchant_name }
            })

            setListDrop(newList)
        } else if (res.data.code == 401) {
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error('Lấy giữ liệu thất bại !', {
                theme: 'colored',
            })
        }
    }

    const handleSubmit = async (event) => {
        const newValue = trimObject(state)

        props.showLoading()
        const res = await createGasStation({
            id: newValue?.id,
            merchant_id: newValue?.merchant_id,
            store_name: newValue?.store_name,
            address: newValue?.address,
            gas_fields: listField,
            store_code: newValue?.store_code,
            queue_name: newValue?.queue_name,

            account: newValue?.account,
            user_name: newValue?.user_name,
            password: newValue?.password,
        })
        props.hideLoading()
        if (res.data.code == 200) {
            history.push('/gas-station')
            if (res.data.code == 200) {
                toast.success('Cập nhật cây xăng thành công!', {
                    theme: 'colored',
                })
            }
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const handleChange = (event) => {
        event.persist()
        setState({
            ...state,
            [event.target.name]: event.target.value,
        })
    }

    const handleDateChange = (date) => {
        setState({ ...state, date })
    }

    const onCreateField = (value) => {
        if (value) {
            console.log('value', value)
            if (listField.findIndex((e) => e.field_name == value) == -1) {
                setListField(
                    [
                        {
                            field_name: value,
                            gas_olines: [],
                        },
                    ].concat(listField)
                )
                setOpenCreate(false)
                toast.success('Thêm trụ thành công!', {
                    theme: 'colored',
                })
            } else {
                toast.warning('Tên trụ xăng đã tồn tại', {
                    theme: 'colored',
                })
            }
        } else {
            toast.warning('Bạn chưa nhập đầy đủ thông tin', {
                theme: 'colored',
            })
        }
    }

    const deletePillar = (index) => {
        let arr = [...listField]
        console.log('arr', arr)
        if (arr[index].id) {
            callApiDeletePillar(arr[index].id)
        }

        arr.splice(index, 1)

        setListField(arr)
        toast.success('Xoá trụ thành công!', {
            theme: 'colored',
        })
    }

    const createFountain = (data, index) => {
        let arr = [...listField]
        //check ma voi
        let flag = true

        arr.map((e, i) => {
            if (e.gas_olines) {
                // if (
                //     e.gas_olines.findIndex(
                //         (e) => e.name.toUpperCase() == data.name.toUpperCase()
                //     ) != -1
                // ) {
                //     toast.warning('Tên vòi xăng đã tồn tại', {
                //         theme: 'colored',
                //     })
                //     flag = false
                // }
                if (
                    e.gas_olines.findIndex(
                        (e) => e.code.toUpperCase() == data.code.toUpperCase()
                    ) != -1
                ) {
                    toast.warning('Mã vòi xăng đã tồn tại', {
                        theme: 'colored',
                    })
                    flag = false
                }
            }
        })
        if (flag) {
            let newList = arr.map((e, i) => {
                if (i == index) {
                    if (e.gas_olines) {
                        console.log('data', data)
                        console.log('e.gas_olines', e.gas_olines)
                        if (
                            e.gas_olines.findIndex(
                                (e) => e.name == data.name
                            ) == -1 &&
                            e.gas_olines.findIndex(
                                (e) => e.code == data.code
                            ) == -1
                        ) {
                            return {
                                ...e,
                                gas_olines: [
                                    {
                                        ...data,
                                    },
                                ].concat(e.gas_olines),
                            }
                        } else {
                            toast.warning('Tên vòi xăng đã tồn tại', {
                                theme: 'colored',
                            })
                            return {
                                ...e,
                                gas_olines: e.gas_olines,
                            }
                        }
                    } else {
                        return {
                            ...e,
                            gas_olines: [
                                {
                                    ...data,
                                },
                            ],
                        }
                    }
                } else return { ...e }
            })

            console.log('newList', newList)
            setListField(newList)
        }
    }
    const deleteFountain = (item, index) => {
        console.log('item', item)

        let arr = [...listField]
        console.log('index', index)

        let newList = arr.map((e, i) => {
            if (item?.field_name == e?.field_name) {
                let temp = [...e?.gas_olines]
                console.log('temp', temp)
                console.log('index', index)
                if (temp[index].id) {
                    callApiDeleteFountain(temp[index].id)
                }

                temp.splice(index, 1)
                console.log('temp', temp)
                return {
                    ...e,
                    gas_olines: temp,
                }
            } else return { ...e }
        })
        console.log('newList', newList)

        setListField(newList)
        toast.success('Xoá vòi thành công!', {
            theme: 'colored',
        })
    }

    const handleCloseCreate = () => {
        setOpenCreate(false)
    }

    const handleCloseUpdate = () => {
        setOpenUpdate(false)
    }
    const onUpdateField = (data) => {
        let arr = [...listField]

        let newList = arr.map((e, i) => {
            if (e.gas_olines.findIndex((e) => e.id == data.id) != -1) {
                // if (e.gas_olines.findIndex((e) => e.name == data.name) == -1) {
                console.log('gas_olines', e.gas_olines)
                const temp = e.gas_olines.map((item) => {
                    if (item.id == data.id) return { ...data }
                    return { ...item }
                })
                return {
                    ...e,
                    gas_olines: temp,
                }
                // } else {
                //     toast.warning('Tên vòi xăng đã tồn tại', {
                //         theme: 'colored',
                //     })

                //     return {
                //         ...e,
                //         gas_olines: e.gas_olines,
                //     }
                // }
            } else {
                return {
                    ...e,
                    gas_olines: e.gas_olines,
                }
            }
        })

        setListField(newList)
        setOpenUpdate(false)
    }

    const countFountain = () => {
        let temp = 0

        listField.map((e) => {
            if (e.gas_olines) {
                temp += e.gas_olines.length
            }
        })

        return temp
    }

    const callApiDeleteFountain = async (id) => {
        props.showLoading()
        const res = await deleteGasOnline({ idGuid: id })
        props.hideLoading()
        if (res.data.code == 200) {
            return true
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
            return false
        }
    }

    const callApiDeletePillar = async (id) => {
        props.showLoading()
        const res = await deleteGasField({ idGuid: id })
        props.hideLoading()
        if (res.data.code == 200) {
            return true
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
            return false
        }
    }

    const {
        store_name,
        address,
        merchant_id,
        store_code,
        queue_name,
        account,
        user_name,
        password,
    } = state

    return (
        <div className="m-sm-30">
            <div className="mb-sm-30">
                <div className="mb-sm-30">
                    <Breadcrumb
                        routeSegments={[
                            {
                                name: 'Danh sách cây xăng',
                                path: '/gas-station',
                            },
                            { name: 'Cập nhật cây xăng' },
                        ]}
                    />
                </div>
                <SimpleCard>
                    <ValidatorForm
                        id="form-create"
                        onSubmit={handleSubmit}
                        onError={() => null}
                    >
                        <Grid container spacing={3}>
                            {merchant_id && (
                                <Grid xs={6} sm={6} item>
                                    <SelectValidator
                                        variant={'outlined'}
                                        label={'Thuộc pháp nhân *'}
                                        disabled={true}
                                        className="mb-4 w-full"
                                        value={merchant_id || ''}
                                        displayEmpty
                                        name="merchant_id"
                                        onChange={handleChange}
                                        validators={['required']}
                                        errorMessages={[
                                            'Không được để trống trường này',
                                        ]}
                                    >
                                        {listDrop.map((e) => (
                                            <MenuItem value={e.id}>
                                                {e.name}
                                            </MenuItem>
                                        ))}
                                    </SelectValidator>
                                </Grid>
                            )}

                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tên cây xăng *"
                                    onChange={handleChange}
                                    type="text"
                                    name="store_name"
                                    value={store_name || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Mã cây xăng *"
                                    onChange={handleChange}
                                    type="text"
                                    name="store_code"
                                    value={store_code || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Mã Queue *"
                                    onChange={handleChange}
                                    type="text"
                                    name="queue_name"
                                    value={queue_name || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid>

                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Địa chỉ *"
                                    onChange={handleChange}
                                    type="text"
                                    name="address"
                                    value={address || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid>

                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tài khoản ATC "
                                    onChange={handleChange}
                                    type="text"
                                    name="account"
                                    value={account || ''}
                                />
                            </Grid>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tên đăng nhập ATC "
                                    onChange={handleChange}
                                    type="text"
                                    name="user_name"
                                    value={user_name || ''}
                                />
                            </Grid>
                            <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Mật khẩu ATC"
                                    onChange={handleChange}
                                    type="text"
                                    name="password"
                                    value={password || ''}
                                />
                            </Grid>

                            {/* <Grid item lg={6} md={6} sm={12} xs={12}>
                                <TextValidator
                                    variant="outlined"
                                    className="mb-4 w-full"
                                    label="Tên cây xăng *"
                                    onChange={handleChange}
                                    type="text"
                                    name="store_name"
                                    value={store_name || ''}
                                    validators={['required']}
                                    errorMessages={[
                                        'Không được để trống trường này',
                                    ]}
                                />
                            </Grid> */}

                            <Grid
                                item
                                container
                                lg={12}
                                md={12}
                                sm={12}
                                xs={12}
                                justify="space-between"
                                style={{
                                    padding: 10,
                                    borderRadius: 5,
                                }}
                            >
                                <Typography variant="h6">
                                    Thông tin trụ xăng
                                </Typography>

                                <Grid
                                    item
                                    container
                                    lg={12}
                                    md={12}
                                    sm={12}
                                    xs={12}
                                    justify="space-between"
                                >
                                    <div>
                                        <Typography variant="subtitle1">
                                            Số lượng trụ: {listField.length}
                                        </Typography>
                                        <Typography variant="subtitle1">
                                            Số lượng vòi: {countFountain()}
                                        </Typography>
                                    </div>
                                    <Button
                                        style={{
                                            width: 140,
                                        }}
                                        onClick={() => {
                                            setOpenCreate(true)
                                        }}
                                        variant="contained"
                                        className={'bg-light-primary'}
                                    >
                                        <span className={'text-primary'}>
                                            Thêm mới trụ
                                        </span>
                                    </Button>
                                </Grid>

                                {listField.map((item, index) => (
                                    <Grid
                                        style={{
                                            border: '1px solid #B9B9B9',
                                            borderRadius: 5,
                                            padding: 10,
                                            marginTop: 20,
                                        }}
                                        lg={12}
                                        md={12}
                                        sm={12}
                                        xs={12}
                                    >
                                        <Grid lg={12} md={12} sm={12} xs={12}>
                                            <div
                                                style={{
                                                    alignItems: 'center',
                                                    justifyContent:
                                                        'space-between',
                                                    display: 'flex',
                                                    marginBottom: 10,
                                                }}
                                            >
                                                <Typography variant="h6">
                                                    {item.field_name}
                                                </Typography>
                                                <Button
                                                    onClick={() => {
                                                        deletePillar(index)
                                                    }}
                                                    variant="contained"
                                                    style={{
                                                        backgroundColor:
                                                            '#FC2B05',
                                                        color: 'white',
                                                    }}
                                                >
                                                    <span>Xoá trụ</span>
                                                </Button>
                                            </div>

                                            <TableContainer component={Paper}>
                                                <Table aria-label="simple table">
                                                    <TableHead>
                                                        <TableRow
                                                            style={{
                                                                backgroundColor:
                                                                    '#F3F3F3',
                                                            }}
                                                        >
                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                    width: 100,
                                                                }}
                                                                align="center"
                                                            >
                                                                STT
                                                            </TableCell>

                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                }}
                                                                align="center"
                                                            >
                                                                Mã vòi
                                                            </TableCell>
                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                }}
                                                                align="center"
                                                            >
                                                                Vòi
                                                            </TableCell>
                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                }}
                                                                align="center"
                                                            >
                                                                Loại nhiên liệu
                                                            </TableCell>
                                                            <TableCell
                                                                style={{
                                                                    borderRight:
                                                                        '0.05px solid #e0e0e0',
                                                                }}
                                                                align="center"
                                                            >
                                                                Sản phẩm
                                                            </TableCell>
                                                            {/* <TableCell align="center">
                                                                Trạng thái hoạt
                                                                động
                                                            </TableCell> */}
                                                            <TableCell
                                                                style={{
                                                                    textAlign:
                                                                        'center',

                                                                    width: 120,
                                                                }}
                                                                align="center"
                                                            >
                                                                Hành động
                                                            </TableCell>
                                                        </TableRow>
                                                    </TableHead>
                                                    <TableBody>
                                                        {item?.gas_olines.map(
                                                            (row, index) => (
                                                                <TableRow
                                                                    key={
                                                                        row.name
                                                                    }
                                                                >
                                                                    <TableCell
                                                                        component="th"
                                                                        scope="row"
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="center"
                                                                    >
                                                                        {index +
                                                                            1}
                                                                    </TableCell>
                                                                    <TableCell
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="right"
                                                                    >
                                                                        {
                                                                            row?.code
                                                                        }
                                                                    </TableCell>
                                                                    <TableCell
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="right"
                                                                    >
                                                                        {
                                                                            row?.name
                                                                        }
                                                                    </TableCell>

                                                                    <TableCell
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="right"
                                                                    >
                                                                        {
                                                                            row?.type_name
                                                                        }
                                                                    </TableCell>
                                                                    <TableCell
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="right"
                                                                    >
                                                                        {
                                                                            row?.product_name
                                                                        }
                                                                    </TableCell>
                                                                    {/* <TableCell
                                                                        style={{
                                                                            borderRight:
                                                                                '0.05px solid #e0e0e0',
                                                                        }}
                                                                        align="right"
                                                                    >
                                                                        {
                                                                            row?.status
                                                                        }
                                                                    </TableCell> */}

                                                                    <TableCell>
                                                                        {row?.id && (
                                                                            <Tooltip title="Cập nhật">
                                                                                <IconButton
                                                                                    onClick={() => {
                                                                                        setOpenUpdate(
                                                                                            true
                                                                                        )
                                                                                        setFountainSelected(
                                                                                            {
                                                                                                ...row,
                                                                                                index,
                                                                                            }
                                                                                        )

                                                                                        console.log(
                                                                                            'heelo',
                                                                                            index
                                                                                        )
                                                                                    }}
                                                                                    //className={classes.button}
                                                                                    aria-label="Delete"
                                                                                >
                                                                                    <Icon color="primary">
                                                                                        edit
                                                                                    </Icon>
                                                                                </IconButton>
                                                                            </Tooltip>
                                                                        )}

                                                                        <Tooltip title="Xoá">
                                                                            <IconButton
                                                                                onClick={() => {
                                                                                    deleteFountain(
                                                                                        item,
                                                                                        index
                                                                                    )
                                                                                    console.log(
                                                                                        'heelo',
                                                                                        index
                                                                                    )
                                                                                }}
                                                                                //className={classes.button}
                                                                                aria-label="Delete"
                                                                            >
                                                                                <Icon color="error">
                                                                                    delete
                                                                                </Icon>
                                                                            </IconButton>
                                                                        </Tooltip>
                                                                    </TableCell>
                                                                </TableRow>
                                                            )
                                                        )}
                                                    </TableBody>
                                                </Table>
                                            </TableContainer>
                                            <CreateFountain
                                                onCreate={(data) => {
                                                    createFountain(data, index)
                                                }}
                                            />
                                        </Grid>
                                    </Grid>
                                ))}
                            </Grid>
                        </Grid>
                        <Grid
                            style={{
                                marginTop: 40,
                            }}
                            container
                            justify={'flex-end'}
                        >
                            <Button
                                style={{
                                    marginRight: 20,
                                }}
                                color="inherit"
                                variant="contained"
                                onClick={() => {
                                    history.goBack()
                                }}
                            >
                                <span className="capitalize">Quay lại</span>
                            </Button>

                            <Button
                                color="primary"
                                variant="contained"
                                type="submit"
                            >
                                <span className="capitalize">Cập nhật</span>
                            </Button>
                        </Grid>
                        <CreateField
                            open={openCreate}
                            handleClose={handleCloseCreate}
                            onAgree={onCreateField}
                        />
                        <UpdateFountain
                            open={openUpdate}
                            handleClose={handleCloseUpdate}
                            onAgree={onUpdateField}
                            data={fountainSelected}
                        />
                    </ValidatorForm>
                </SimpleCard>
            </div>
        </div>
    )
}

const mapStateToProps = (state) => {
    return {}
}
export default connect(mapStateToProps, { showLoading, hideLoading })(
    SimpleForm
)
