
import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Row, Col, Tag, Pagination, Modal, DatePicker, Card, Avatar } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import styles from '../../style/GoodsList.less';
import router from 'umi/router';
import AuthButton from '../../../components/AuthButton';
import apis from '../../../services/apis';
import request from '../../../utils/request'
import Styles from './style.less';
import BuildingSelect from '@/components/SelectButton/BuildSelect';
import CustomerChange from '../components/CustomerChange'
import EditIcon from '@/components/EditIcon';

const { Meta } = Card;
const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

// 跳转到编辑商品
const toEditStaff = userId => () => {
  router.push({
    pathname: '/staff/editStaff',
    query: {
      userId,
    },
  });
}


/**
 *卡片
 *
 * @returns
 */
const CartBody = props => {
  const { data } = props
  const [visible, setVisible] = useState(false)
  // console.log("data11:", data)

  const confirm = data => () => {
    // console.log(data, "11111")
    if (data.status === 1) {
      if (data.isConsultant) {
        request({ ...apis.staff.check, params: { userId: data.userId, personId: data.consultantPersonId, buildingId: data.buildingId } }).then(res => {
          if (res.length > 0) {
            Modal.confirm({
              title: '此置业顾问下有私客，是否转移私客？',
              okText: '确认',
              cancelText: '取消',
              onOk() {
                setVisible(true)
              },
            });
          } else {
            const titleMessahe = data.isConsultant ? '停用后此员工无法继续登录后台（若为置业顾问停用后在小程序端将成为普通用户）确认进行停用操作？' : '停用后此员工无法继续登录后台,确认进行停用操作？';
            Modal.confirm({
              title: titleMessahe,
              okText: '确认',
              cancelText: '取消',
              onOk() {
                request({ ...apis.staff.change, urlData: { id: data.userId, type: 'off' } }).then(res => {
                  message.info('操作成功')
                  props.onFresh()
                })
              },
            });
          }
        })
      } else {
        const titleMessahe = data.isConsultant ? '停用后此员工无法继续登录后台（若为置业顾问停用后在小程序端将成为普通用户）确认进行停用操作？' : '停用后此员工无法继续登录后台,确认进行停用操作？';
        Modal.confirm({
          title: titleMessahe,
          okText: '确认',
          cancelText: '取消',
          onOk() {
            request({ ...apis.staff.change, urlData: { id: data.userId, type: 'off' } }).then(res => {
              message.info('操作成功')
              props.onFresh()
            })
          },
        });
      }
    } else {
      Modal.confirm({
        title: '确认启用该角色？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          request({ ...apis.staff.change, urlData: { id: data.userId, type: 'on' } }).then(res => {
            message.info('操作成功')
            props.onFresh()
          })
        },
      });
    }
  }

  //迁移私客成功回调
  const moveSuccess = (e) => {
    setVisible(false)
    if (e === 'success') {
      confirm(data)()
    }
  }

 
  return (
    <div>
      <Card className={Styles.card}>
        <div>
          <Avatar src={data.photo} style={{ width: '0.48rem', height: '0.48rem' }} />
          <AuthButton name="admin.user.put" noRight={null}>
            <Button type="link" style={{ color: '#FF925C', fontSize: '0.106rem', position: 'absolute', top: '40px', left: '0.56rem' }} onClick={toEditStaff(data.userId)}>
              <EditIcon text="编辑" color='#ff925c' type="edit"></EditIcon>
            </Button>
          </AuthButton>
          {/* <Button type="link" style={{ fontSize: ' 0.106rem', color: '#cacaca', position: 'absolute', top: '40px', right: '0' }} onClick={() => departure(data)}>
            离职
                  <Icon type="exclamation-circle" style={{ color: '#C0C4CC', marginLeft: '0.04rem' }} />
          </Button> */}
          <AuthButton name="admin.user.publish" noRight={null}>
            <Button type="link" style={{ fontSize: ' 0.106rem', color: '#cacaca', position: 'absolute', top: '40px', right: '0' }} onClick={confirm(data)}>
              {data.status === 1 ? <EditIcon text="停用" color='#FF4A4A' type="stop"></EditIcon> : <EditIcon text="启用" color='#ff925c' type="start"></EditIcon>}

            </Button>
          </AuthButton>
        </div>
        <div>

          <span>
            {
              data.taTagsList.map((item, index) => <Tag className={Styles.cardTag} color={item.tagColor}>{item.tagName}</Tag>)
            }
          </span>

          <p className={Styles.cardText} >姓名 : {data.userName}
          </p>
          {/* <p className={Styles.statusText} > 状态 : {data.status === 1 ? '启用' : '停用'} </p> */}
          <p className={Styles.statusText} > 绑定状态 : {data.miniStatus === 1 ? '已绑定' : '未绑定'} </p>
          <p className={Styles.phoneText} >
            电话 : {data.phone}
          </p>
        </div>

      </Card>
      <Modal
        visible={visible}
        title="分配归属"
        onCancel={() => setVisible(false)}
        footer={null}
        width={900}
      >
        <CustomerChange userId={data.userId} consultantPersonId={data.consultantPersonId} buildingId={data.buildingId} onSuccess={moveSuccess} />
      </Modal>
    </div>
  )
}

const header = props => {
  const [tempData, setTempData] = useState({ records: [] })
  useEffect(() => {
    getList({ pageNum: 1, pageSize: 8 });
  }, [])

  const getList = params => {
    request({ ...apis.staff.taUser, params: { ...params } }).then(data => {
      console.log(data, 'listData')
      setTempData(data)
    })
  }

  // 分页
  const onChange = pageNumber => {
    getList({ pageNum: pageNumber, pageSize: 8, ...props.form.getFieldsValue() });
  }

  // 提交事件
  const handleSubmit = (e, props) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log('提交数据: ', values)
        getList({ pageNum: 1, pageSize: 8, ...values })
      }
    });
  }

  // 重置搜索
  function handleReset() {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 8 });
  }

  const { getFieldDecorator } = props.form
  return (

    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('buildingId')(
            <BuildingSelect />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('userName')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="姓名"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('phone')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="电话"
            />,
          )}
        </Form.Item>

        <Form.Item>

          {getFieldDecorator('status')(
            <Select style={{ width: '180px' }} placeholder="状态" >
              <Option value="1">启用</Option>
              <Option value="9">停用</Option>
            </Select>,
          )}
        </Form.Item>

        <Form.Item>

          {getFieldDecorator('isConsultant')(
            <Select style={{ width: '180px' }} placeholder="是否置业顾问" >
              <Option value="0">非置业顾问</Option>
              <Option value="1">置业顾问</Option>
            </Select>,
          )}
        </Form.Item>

        <Form.Item>

          {getFieldDecorator('miniStatus')(
            <Select style={{ width: '180px' }} placeholder="是否绑定" >
              <Option value="0">未绑定</Option>
              <Option value="1">已绑定</Option>
            </Select>,
          )}
        </Form.Item>

        <Form.Item>
          <AuthButton name="admin.user.search" noRight={null}>
            <Button type="primary" htmlType="submit" className={styles.searchBtn}>
              搜索
          </Button>
          </AuthButton>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
      <AuthButton name="admin.user.add" noRight={null}>
        <Button type="danger" style={{ margin: '20px 0', padding: '2px 36px' }} onClick={toEditStaff()}>新增</Button>
      </AuthButton>
      <Row style={{ padding: ' 0 10px' }}>
        {
          tempData.records.filter(f => f.isAdmin != 1).map((item, index) => (
            <Col span={6}>
              <CartBody data={item} onFresh={() => getList({ pageNum: 1, pageSize: 8 })} key={item.userId} />
            </Col>
          ))
        }
      </Row>

      {/* 分页  */}
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Pagination showQuickJumper defaultCurrent={1} pageSize={8} total={tempData.total} onChange={onChange} current={tempData.current} />
      </div>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
