import { useEffect, useState, useRef } from 'react'
import { Input, Button, Space, Popover, Switch, Image, App } from 'antd'
import { getCoupon, setCoupon } from './request'
import Add from '@/assets/images/icon/add.png'
import coupon from '@/assets/images/icon/coupon.png'
import coupon2 from '@/assets/images/icon/coupon2.png'
import { useSelector } from 'react-redux'
import AppList from '@/components/list'
import FormDrawer from './components/FormDrawer'
import SendCouponDrawer from './components/SendCouponDrawer'
import * as api from './api'

const Coupon = () => {
  const { modal } = App.useApp()

  const appListRef = useRef(null)
  const reload = async () => {
    await appListRef.current.handleReload(true)
  }
  const [drawerOpen, setDrawerOpen] = useState(false)
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)

  // 操作某一项的id
  const [id, setId] = useState('')

  const [switchFlag, setSwitchFlag] = useState(false)
  const [couponList, setCouponList] = useState([])
  const [sendCouponDrawerOpen, setSendCouponDrawerOpen] = useState(false)
  // 添加
  const handleAdd = () => {
    setId('')
    setDrawerOpen(true)
  }
  // 编辑
  const handleEdit = async id => {
    setId(id)
    setDrawerOpen(true)
  }
  const onClose = () => {
    setDrawerOpen(false)
  }
  // 删除
  const handleDelete = async id => {
    modal.confirm({
      title: '提示',
      content: '优惠券将永久删除，是否继续?',
      onOk: async () => {
        await api.delCoupon({ id })
        reload()
      }
    })
  }

  // 获取优惠券开关状态
  const handleCoupon = async () => {
    const { coupon_switch } = await getCoupon()
    coupon_switch == '1' ? setSwitchFlag(true) : setSwitchFlag(false)
  }
  const [swithcLoad, setSwitchLoad] = useState(false)
  // 改变优惠券开关
  const changeCoupon = async val => {
    setSwitchLoad(true)
    let coupon_switch = val ? '1' : '0'
    const bool = await setCoupon({ coupon_switch })
    setTimeout(() => {
      setSwitchLoad(false)
    }, 500)
    handleCoupon()
  }

  useEffect(() => {
    handleCoupon()
  }, [])

  const remote = {
    request: api.getList,
    afterRequest(data) {
      setCouponList(data.list)
      return data
    }
  }
  const filters = [
    {
      label: '优惠券名称',
      name: 'name',
      element: <Input placeholder="请输入优惠券名称" allowClear />
    }
  ]
  const columns = [
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      dataIndex: 'id'
    },
    {
      title: '优惠券名称',
      key: 'name',
      align: 'center',
      dataIndex: 'name',
      width: 200,
      render: text => (
        <Popover content={text} overlayStyle={{ maxWidth: '400px' }}>
          <div
            style={{
              display: '-webkit-box',
              WebkitLineClamp: '2',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              textAlign: 'center'
            }}>
            {text}
          </div>
        </Popover>
      )
    },
    {
      title: '达标金额',
      key: 'norm_price',
      align: 'center',
      dataIndex: 'norm_price'
    },
    {
      title: '满减金额',
      key: 'reduced_price',
      align: 'center',
      dataIndex: 'reduced_price'
    },
    {
      title: '有效期开始时间',
      key: 'start_time',
      align: 'center',
      dataIndex: 'start_time'
    },
    {
      title: '有效期结束时间',
      key: 'end_time',
      align: 'center',
      dataIndex: 'end_time'
    },
    {
      title: '领取人数',
      key: 'receive_num',
      align: 'center',
      dataIndex: 'receive_num'
    },
    {
      title: '使用人数',
      key: 'use_num',
      align: 'center',
      dataIndex: 'use_num'
    },
    {
      title: '操作',
      key: 'handle',
      align: 'center',
      dataIndex: 'handle',
      render: (_, { id }) => {
        return (
          <Space>
            {operationPermissionsList.includes('/setting/coupon/getInfoById') && <Button onClick={() => handleEdit(id)}>编辑</Button>}
            {operationPermissionsList.includes('/setting/coupon/del') && <Button onClick={() => handleDelete(id)}>删除</Button>}
          </Space>
        )
      }
    }
  ]

  const filterAside = (
    <Space>
      <label htmlFor="coupon">优惠券开关</label>
      <Switch
        checked={switchFlag}
        loading={swithcLoad}
        onChange={changeCoupon}
        disabled={!operationPermissionsList.includes('/setting/coupon/getCoupon')}></Switch>
      {operationPermissionsList.includes('/setting/coupon/add') && (
        <Button
          type="primary"
          disabled={!switchFlag}
          ghost
          icon={
            <img
              style={{
                background: !switchFlag,
                display: 'inline-block',
                width: '13px',
                height: '11px',
                pointerEvents: 'none'
              }}
              src={!switchFlag ? coupon2 : coupon}
            />
          }
          onClick={() => setSendCouponDrawerOpen(true)}>
          优惠券发放
        </Button>
      )}
      {operationPermissionsList.includes('/setting/coupon/give') && (
        <Button
          type="primary"
          ghost
          icon={
            <span
              style={{
                display: 'inline-block',
                width: '13px',
                height: '12px',
                pointerEvents: 'none'
              }}>
              <Image src={Add} />
            </span>
          }
          onClick={handleAdd}>
          添加
        </Button>
      )}
    </Space>
  )

  return (
    <div className="classify">
      <AppList {...{ remote, filters, columns, filterAside }} ref={appListRef}></AppList>
      {/* 添加编辑 */}
      <FormDrawer open={drawerOpen} id={id} onClose={onClose} onComplete={reload}></FormDrawer>
      {/* 优惠券发送 */}
      <SendCouponDrawer open={sendCouponDrawerOpen} couponList={couponList} onClose={() => setSendCouponDrawerOpen(false)}></SendCouponDrawer>
    </div>
  )
}

export default Coupon
