import React, { useState, useEffect } from 'react';
import { Button, notification, Tree, message, Spin } from 'antd';
import md5 from 'md5';
import moment from 'moment';
import router from 'umi/router';
import XForm, { FieldTypes } from '../../../components/XForm';
import { fetch, apis } from '../../../utils/request';
import SelectCity from '../CitySelect';
import ImageUpload from '../../../components/uploadImage/ImageUpload';


const defaultPass = 'abc@123';
const saveUser = fetch(apis.member.save)
const updateUser = fetch(apis.member.update)
const getCityTree = fetch(apis.member.getTree)

export default props => {
  const { TreeNode } = Tree;
  const [data, setData] = useState({})
  const [submitting, setSubmitting] = useState(false)
  const user = props.data;
  console.log('user: ', user)
  // 初始化的值
  const [tree, setTree] = useState([])
  // 城市的值
  const [selectCityTree, setSelectCityTree] = useState([])
  
  // 省份的值
  // const [selectProvinceTree, setSelectProvinceTree] = useState([])

  useEffect(() => {
    getCity()
    if (user) {
      setSelectCityTree([''])
      setSelectCityTree(user.selectCityTree)
    }
  }, [user])

  const getCity = () => {
    getCityTree().then((user) => {
      console.log('user.tdCityLis', user.tdCityList)
      setTree(user.tdCityList)
      }).catch(() => setSubmitting(false))
    }

  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  // 选择城市
  const onCheck = (checkedKeys, info) => {
    setSelectCityTree(checkedKeys)
    console.log('onCheck', checkedKeys, info);
  };

  const fields = [
    {
      label: '公司名称',
      name: 'orgName',
      type: FieldTypes.Text,
      value: user.orgName,
    },
    {
      label: '公司水印',
      name: 'waterMark',
      render: () => <ImageUpload onChange={e => console.log(e,"66")}/>,
      value: user.waterMark,
    },
    {
      label: '用户名称',
      name: 'userName',
      type: FieldTypes.Text,
      rules: [
        {required: true, message: '请填写用户名称'}
      ],
      value: user.userName,
    },
    {
      label: '手机号',
      name: 'phone',
      type: FieldTypes.Text,
      rules: [
        { required: true, message: '请填写手机号' },
        { len: 11, message: '手机号格式不正确' },
      ],
      value: user.phone,
    },
    {
      label: '登录名称',
      name: 'loginName',
      type: FieldTypes.Text,
      placeholder: '不填, 默认使用手机号',
      extra: `默认登录密码 ${defaultPass}`,
      value: user.loginName,
    },
    {
      label: '头像',
      name: 'avatar',
      type: FieldTypes.ImageUploader,
      extra: '建议图片大小 128 * 128',
      value: user.avatar,
    },
    {
      label: '有效期',
      name: 'expDate',
      type: FieldTypes.DatePicker,
      rules: [
        { required: true, message: '请选择有效期' },
      ],
      value: moment(user.expDate),
    },

    {
      label: <span><span style={{ color: 'red', fontSize: '22px' }}>*</span>维护城市</span>,
      name: 'cityId',
      render: row=> <Tree
        checkable
        // 展开指定节点
        // expandedKeys={selectProvinceTree}
        // 选择节点,但同时会包含父节点
        checkedKeys={selectCityTree}
        //  defaultSelectedKeys={['420100']}
        onSelect={onSelect}
        onCheck={onCheck}
      >
      <TreeNode title="全部">
      {tree.map(item => (
        <TreeNode title={item.name} key={item.id}>
           {item.children.map(itemCity => (
            <TreeNode
                title={<span style={{ color: '#1890ff' }}>{itemCity.name}</span>}
                key={itemCity.id}
              />
          ))}
        </TreeNode>
       ))}
</TreeNode>
      </Tree>,
    },

    {
      label: '默认城市',
      name: 'defaultCityId',
      rules: [
        { required: true, message: '默认城市' },
      ],
      value: user.defaultCityId,
      render: (row, index) => <SelectCity />,
    },

    {
      label: '维护项目数量',
      name: 'orgNum',
      type: FieldTypes.Number,
      rules: [
        { required: true, message: '请输入维护项目数量' },
        {
          pattern: new RegExp('^[0-9]*$'),
          message: '只允许输入数字',
        },
      ],
      value: user.orgNum,
    },
  ]

  const handleSubmit = val => {
    const dt = {
      ...val,
      loginName: val.loginName || val.phone,
      loginPassword: md5(defaultPass),
    }
    if (selectCityTree.length <= 0) {
      message.error('维护城市必须存在一个')
      return
    }

    const data = { ...user, ...dt, selectCityTree }
    if (data.orgNum <= 0) {
      message.error('维护项目数量必须大于0')
      return
    }
    
    setSubmitting(true)
    if (user && user.userId) {
      updateUser({ urlData: { id: user.userId }, data }).then((user) => {
        setSubmitting(false)
        notification.success({message: '编辑信息成功'})

        if (typeof props.onChange === 'function') {
          props.onChange(data)
        }

      }).catch(() => setSubmitting(false))
    } else {
      saveUser({ data }).then((user) => {
        setSubmitting(false)
        notification.success({message: '新建信息成功'})
        router.push(`/member/edit/${user.userId}`)
      }).catch(() => setSubmitting(false))
    }
  }

  const handleCancel = () => {
    if (typeof props.onCancel === 'function') {
      props.onCancel()
    }
  }

  return (
  <><Spin spinning={ submitting } size="large"><XForm onSubmit={handleSubmit} onCancel={handleCancel} fields={fields} submitting={submitting}></XForm></Spin></>)
}
