import React, { useEffect, useState } from 'react'
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Pagination,
  Drawer,
  Form,
  Select,
  Image,
  Rate,
  Modal
} from 'antd'
const { TextArea } = Input
const { RangePicker } = DatePicker
import PaginationCom from '@/common/Pagination'
import { getList, refund } from './request'
import TableCom from '@/common/TableCom/index'
import reset from '@/assets/images/icon/reset.png'
import filter from '@/assets/images/icon/filter.png'
import add from '@/assets/images/icon/add.png'
import imports from '@/assets/images/icon/import.png'
import reload from '@/assets/images/icon/reload.png'
import wx from '@/assets/images/vx.png'
import zhifu from '@/assets/images/zhifu.png'
import money from '@/assets/images/money.png'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'
const Audit = () => {
  const [data, setData] = useState([])
  const [page_size, setpage_size] = useState(10)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [isEdit, setIsEdit] = useState(false)
  const [id, setId] = useState(0)
  const [filterObj, setfilterObj] = useState({
    book_name: '',
    status: null,
    pay_type: null,
    start_pay: '',
    end_pay: ''
  })
  const [dateVal, setDateVal] = useState('')
  // 获取操作权限
  const { operationPermissionsList } = useSelector(state => state.user)
  // 过滤
  const handleFilter = (flag, val) => {
    if (flag == 'startandend') {
      let val2 = val || []
      filterObj['start_pay'] = parseInt(new Date(dayjs(val2[0]).format('YYYY-MM-DD') + ' 00:00:00').getTime() / 1000)
      const endDate = new Date(dayjs(val2[1])).getDate() + 1
      const endTime = parseInt(new Date(dayjs(val2[1]).format('YYYY-MM-DD') + ' 23:59:59').getTime() / 1000)
      filterObj['end_pay'] = endTime
      setDateVal(val)
      if (!val2.length) {
        delete filterObj['start_pay']
        delete filterObj['end_pay']
      }
    } else {
      filterObj[flag] = val
    }
    for (const key in filterObj) {
      if (!filterObj[key]) {
        delete filterObj[key]
      }
    }
    setfilterObj({ ...filterObj })
    if (!val) init(filterObj)
  }
  // 退款
  const handleRefund = async (obj = {}) => {
    const bool = await refund({ id, ...obj })
    if (!bool) return
    init()
    setShowReply(false)
  }
  const [form] = Form.useForm()
  const onChange = pageNumber => {
    setLoading(true)
    setPage(pageNumber)
    setLoading(false)
  }
  const handleEdit = () => {
    setIsEdit(true)
  }
  const onClose = () => {
    setIsEdit(false)
  }
  const submitForm = obj => {
    console.log(obj)
  }
  const init = async (obj = {}) => {
    setLoading(true)
    const { total, list } = await getList({ ...obj, page, page_size })
    setTotal(total)
    setData(list || [])
    setLoading(false)
  }
  const [showReply, setShowReply] = useState(false)
  const columns = [
    {
      title: '订单编号',
      key: 'id',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '书籍名称',
      key: 'book_name',
      dataIndex: 'book_name',
      align: 'center',
      width: 150
    },
    {
      title: '购买人',
      key: 'members_name',
      dataIndex: 'members_name',
      align: 'center'
    },
    {
      title: '总金额',
      key: 'total_price',
      dataIndex: 'total_price',
      align: 'center'
    },
    {
      title: '优惠券抵扣金额',
      key: 'coupon_price',
      dataIndex: 'coupon_price',
      align: 'center',
      width: 140
    },
    {
      title: '积分抵扣金额',
      key: 'integral_price',
      dataIndex: 'integral_price',
      align: 'center',
      width: 140
    },
    {
      title: '实际付款金额',
      key: 'final_total_price',
      dataIndex: 'final_total_price',
      align: 'center',
      width: 140
    },
    {
      title: '下单时间',
      key: 'create_time',
      dataIndex: 'create_time',
      align: 'center'
    },
    {
      title: '支付时间',
      key: 'pay_time',
      dataIndex: 'pay_time',
      align: 'center'
    },
    {
      title: '结算状态',
      key: 'status_name',
      dataIndex: 'status_name',
      align: 'center'
    },
    {
      title: '支付方式',
      key: 'pay_type_name',
      dataIndex: 'pay_type_name',
      align: 'center',
      width: 100,
      render(_, { pay_type_name }) {
        if (pay_type_name == '微信') {
          return <img src={wx} width={30}></img>
        } else if (pay_type_name == '支付宝') {
          return <img width={30} src={zhifu}></img>
        } else {
          return <img src={money} width={30} />
        }
      }
    },
    {
      title: '评价',
      key: 'rating',
      dataIndex: 'rating',
      align: 'center',
      width: 135,
      render(_, { rating }) {
        return <Rate disabled allowHalf style={{ width: 135 }} value={rating}></Rate>
      }
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      align: 'center',
      render(_, { status, id }) {
        return (
          operationPermissionsList.includes('/books/order-management/refund') &&
          status == 3 && (
            <Button
              onClick={() => {
                setShowReply(true)
                setId(id)
              }}>
              退款
            </Button>
          )
        )
      }
    }
  ]
  const handleReset = () => {
    setfilterObj({ book_name: '', status: null, pay_type: null })
    setDateVal('')
    init()
  }
  return (
    <div>
      <Row justify={'space-between'}>
        <Col className="form-devices-inline">
          <Form layout="inline">
            <Form.Item label="书籍名称">
              <Input
                allowClear
                autoComplete="off"
                placeholder="请输入书籍名称"
                id="name"
                value={filterObj.book_name}
                onChange={ev => handleFilter('book_name', ev.target.value)}></Input>
            </Form.Item>
            <Form.Item label="支付状态">
              <Select
                allowClear
                placeholder="请选择支付状态"
                value={filterObj.status}
                onChange={ev => handleFilter('status', ev)}
                style={{ width: 160 }}>
                <Select.Option value="1">待支付</Select.Option>
                <Select.Option value="2">取消支付</Select.Option>
                <Select.Option value="3">已支付</Select.Option>
                <Select.Option value="4">已退款</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="支付方式">
              <Select
                allowClear
                placeholder="请选择支付方式"
                value={filterObj.pay_type}
                onChange={ev => handleFilter('pay_type', ev)}
                style={{ width: 160 }}>
                <Select.Option value="1">微信</Select.Option>
                <Select.Option value="2">支付宝</Select.Option>
                <Select.Option value="3">紫荆币</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="支付时间">
              <RangePicker
                id="createTime"
                allowClear
                autoComplete="off"
                value={dateVal}
                onChange={ev => handleFilter('startandend', ev)}></RangePicker>
            </Form.Item>
            <Space>
              <Button
                type="primary"
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '11px',
                      height: '10px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={reset} />
                  </span>
                }
                onClick={handleReset}>
                重置
              </Button>
              <Button
                type="primary"
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={filter} />
                  </span>
                }
                ghost
                onClick={() => {
                  setPage(1)
                  Object.values(filterObj).some(item => item) ? init(filterObj) : init()
                }}>
                筛选
              </Button>
              <Button
                type="primary"
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '10px',
                      height: '12px',
                      pointerEvents: 'none'
                    }}>
                    <Image src={reload} />
                  </span>
                }
                onClick={() => {
                  Object.values(filterObj).some(item => item) ? init(filterObj) : init()
                }}>
                刷新
              </Button>
            </Space>
          </Form>
        </Col>
        <Col></Col>
      </Row>
      <br />
      {TableCom({ columns, loading, data })}
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        setPage={setPage}
        init={init}
        filterObj={filterObj}
      />
      <Drawer
        open={showReply}
        onCancel={() => {
          setShowReply(false)
        }}
        maskClosable={false}
        footer={null}
        centered
        mask={false}
        onClose={() => {
          setShowReply(false)
        }}
        keyboard={false}>
        <Form
          form={form}
          onFinish={handleRefund}
          labelCol={{ span: 4 }}
          style={{ textAlign: 'center', padding: '10px 0 18px', fontSize: 16 }}>
          <Form.Item label="退款原因" name="refund_reason">
            <TextArea
              placeholder="请输入退款原因"
              autoSize={{
                minRows: 3,
                maxRows: 5
              }}></TextArea>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 3 }}>
            <Row gutter={20} justify={'center'}>
              <Col>
                <Button onClick={() => setShowReply(false)}>取消</Button>
              </Col>
              <Col>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
              </Col>
            </Row>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default Audit
