import React, { useState, useEffect } from 'react';

import { Input, Card, message, Radio, Select, Modal } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import BuildSelect from '@/components/SelectButton/BuildSelect'
import router from 'umi/router';
import { FieldTypes, createForm } from '@/components/XForm';
import Wangedit from '@/components/Wangedit/Wangedit'
// import channels from './channelList.less';
// import Tagss from '../components/Tagss.jsx';
import apis from '@/services/apis';
import request from '@/utils/request'
import BuildingSelection from '../components/BuildingSelection'

const { TextArea } = Input;
const { Option } = Select;
let consultantChecked = false;

const setExtraData = (data) => {
  consultantChecked = data.isConsultant
}

const handleFormValueChange = (props, changedValues, allValues) => {
    setExtraData(allValues)
}

const XForm = createForm({ onValuesChange: handleFormValueChange })

/**
 *
 *
 * @param {*} props
 * @returns
 */
const StaffEdit = (props) => {
  const userId = props.location.query.userId
  const [userData, setUserData] = useState({})
  const [tagData, setTagData] = useState([])
  const [roleData, setRoleData] = useState([])
  const [buildData, setBuildData] = useState([])
  const [visible, setVisible] = useState(false)

  const getTagList = () => {
    request({ ...apis.staff.taTags, params: { pageNum: 1, pageSize: 999 } }).then((data) => {
      setTagData(data.records)
    })
  }

  const getRoleList = () => {
    request({ ...apis.role.getRoleList, params: { pageNum: 1, pageSize: 999 } }).then((data) => {
      console.log(data)
      setRoleData(data.records)
    })
  }

  //获取项目列表
  const getBuildList = e => {
    request({ ...apis.building.buildingSelect, params: { pageNum: 1, pageSize: 999 } }).then(data => {
        setBuildData(data)
    })
  }

  // 查询列表
  const getUserData = (userId) => {
    request({ ...apis.staff.getTaUser, urlData: { id: userId } }).then((data) => {
      consultantChecked = data.isConsultant
      setUserData(data)
    })
  }

  if(userData.buildingIds && buildData.length > 0 && !consultantChecked){
      const newBuildings = userData.buildingIds.filter(x => buildData.filter(it => it.buildingId === x)[0])
      userData.buildingIds = newBuildings
  }

  if(userData.roleIds && roleData.length > 0){
    const newRoleIds = userData.roleIds.filter(x => roleData.filter(it => it.roleId === x)[0])
      userData.roleIds = newRoleIds
  }

  useEffect(() => {
    getTagList();
    getRoleList();
    getBuildList();
    if (userId) {
      getUserData(userId);
    }
  }, [])

  const tagsChange = (value) => {
    console.log(`selected ${value}`);
  }

  const handleSubmit = val => {
    if (userId) {
      request({ ...apis.staff.updateTaUser, urlData: { id: userId }, data: val, }).then((data) => {
        console.log(data, "tauser")
        message.info("保存成功")
        router.go(-1)
      }).catch(error => {
        // message.info(error.message)
      })
    } else {
      request({ ...apis.staff.addTaUser, data: val, }).then((data) => {
        console.log(data, "tauser")
        message.info("保存成功")
        router.go(-1)
      }).catch(error => {
        // message.info(error.message)
      })
    }
  }

  const photoBeforeUpload = (file) => {
    // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    // if (!isJpgOrPng) {
    //   message.error('请上传 JPG/PNG 格式的图片!');
    // }
    console.log(file.size, file.size / 1024)
    const isLt100k = (file.size / 1024) < 100;
    if (!isLt100k) {
      message.error('请上传小于100k的图片!');
    }
    return isLt100k;
  }

  //授权项目改变
  const consultantBuildingChange =(e) => {
    if(userData.isConsultant){
      request({ ...apis.staff.check, params: { userId: userData.userId, personId: userData.consultantPersonId, buildingId: userData.buildingId } }).then(res => {
        if(res.length > 0){
          Modal.confirm({
            title: '此置业顾问下有私客，是否转移私客？',
            okText: '确认',
            cancelText: '取消',
            onOk () {
              setVisible(true)
            },
          });
        }
     })
    }
  }

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

  const fields = [


    
    // {
    //   label: '姓名',
    //   name: 'userName',
    //   type: FieldTypes.Text,
    //   value: userData.userName,
    //   rules: [
    //     { required: true, message: '请输入姓名' },
    //   ]
    // },
    // {
    //   label: '公司',
    //   name: 'orgName',
    //   type: FieldTypes.Text,
    //   placeholder: '请输入公司名称',
    //   value: userData.orgName,
    //   rules: [
    //     { required: true, message: '请输入公司名称' },
    //   ]
    // },
    // {
    //   label: '部门',
    //   name: 'department',
    //   type: FieldTypes.Text,
    //   placeholder: '请输入部门',
    //   value: userData.department,
    //   rules: [
    //     { required: true, message: '请输入部门' },
    //   ]
    // },
    // {
    //   label: '职位',
    //   name: 'position',
    //   type: FieldTypes.Text,
    //   placeholder: '请输入职位',
    //   value: userData.position,
    //   rules: [
    //     { required: true, message: '请输入职位' },
    //   ]
    // },
    // {
    //   label: '是否置业顾问',
    //   name: 'isConsultant',
    //   type: FieldTypes.Switch,
    //   value: userData.isConsultant,
    //   props: {disabled: userData.isConsultant},
    // },
    // {
    //   label: '电话',
    //   name: 'phone',
    //   type: FieldTypes.Text,
    //   placeholder: '请输入电话号码',
    //   value: userData.phone,
    //   rules: [
    //     {
    //         required: true,
    //         pattern: new RegExp('^1[0-9]{10}$'),
    //         message: '请输入正确的电话号码',
    //     },
    //   ]
    // },
    // {
    //   label: '登录名',
    //   name: 'loginName',
    //   type: FieldTypes.Text,
    //   placeholder: '请输入登录名',
    //   value: userData.loginName,
    //   // hidden: () => consultantChecked,
    //   help: '默认密码：123456',
    // },
    // {
    //   label: '角色',
    //   name: 'roleIds',
    //   render: <Select
    //     mode="multiple"
    //     style={{ width: '100%' }}
    //     placeholder="请选择标签"
    //     onChange={tagsChange} >
    //     {roleData.map(item => (
    //       <Select.Option key={item.roleId} value={item.roleId}>
    //         {item.roleName}
    //       </Select.Option>
    //     ))}
    //   </Select>,
    //   value: userData.roleIds,
    // },
    // {
    //   label: '授权项目',
    //   name: 'buildingId',
    //   render: <BuildingSelection userData={userData} />,
    //   value: userData.buildingId,
    //   hidden: () => !consultantChecked,
    //   rules: [
    //     { required: true, message: '请选择授权项目' },
    //   ]
    // },
    // {
    //   label: '授权项目',
    //   name: 'buildingIds',
    //   render: <Select
    //     mode="multiple"
    //     showSearch
    //     style={{ width: '100%' }}
    //     placeholder="请选择授权项目"
    //     filterOption={(input, option) =>
    //       option.props.children && option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    //     }
    //     >
    //     {buildData.map(item => (
    //       <Select.Option key={item.buildingId} value={item.buildingId}>
    //         {item.buildingName}
    //       </Select.Option>
    //     ))}
    //   </Select>,
    //   value: userData.buildingIds,
    //   hidden: () => consultantChecked,
    //   rules: [
    //     { required: true, message: '请选择授权项目' },
    //   ]
    // },
    // {
    //   label: '置业顾问头像',
    //   name: 'photo',
    //   type: FieldTypes.ImageUploader,
    //   extra: '建议图片尺寸：320*320px，比例1:1,格式：jpg，用于置业顾问头像,限制大小：100k',
    //   value: userData.photo,
    //   beforeUpload: (e) => photoBeforeUpload(e),
    //   rules: [
    //     { required: true, message: '请选择头像' },
    //   ]
    // },
    // {
    //   label: '简介',
    //   name: 'description',
    //   render: <TextArea  ></TextArea>,
    //   value: userData.description
    //   // className={channels.inpuitTxt}
    // },
    // {
    //   label: '状态',
    //   name: 'status',
    //   render: <Radio.Group initialValue="1" buttonStyle="solid">
    //     <Radio.Button value="9">禁用</Radio.Button>
    //     <Radio.Button value="1">启用</Radio.Button>
    //   </Radio.Group>,
    //   value: userData.status != null ? userData.status.toString() : "1"
    // },
    // {
    //   label: '权重',
    //   name: 'weight',
    //   type: FieldTypes.Number,
    //   render: <Input type="number" style={{ width: 150}} />,
    //   value: userData.weight,
    //   help: '数字越大越靠前',
    // },
  ]


  return <Card>
            <XForm  onSubmit={handleSubmit} fields={fields} onCancel={() => router.go(-1)}></XForm>

        </Card>
}

export default StaffEdit
