import React, { useState, useEffect } from 'react';
import { Input, Card, message, Select } from 'antd';
import InstitutionSelect from '@/components/SelectButton/InstitutionSelect';
import router from 'umi/router';
import { FieldTypes, createForm } from '@/components/XForm';
import apis from '@/services/apis';
import request from '@/utils/request';
import AuthButton from '@/components/AuthButton';
import BuildingSelection from '../components/BuildingSelection';

const { TextArea } = Input;

const XForm = createForm();

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

  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 =;
      setIsConsultant(data.isConsultant);
      setUserData(data);
    });
  };

  if (userData.buildingIds && buildData.length > 0 && !isConsultant) {
    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(() => {
    getRoleList();
    getBuildList();
    if (userId) {
      getUserData(userId);
    }
  }, []);

  const handleSubmit = val => {
    console.log(val, userId, '----------111------------');
    // val.institutionIdLis =  val?.institutionIdLis?.split(',')
    // console.log(val,userId,'----------------------')
    if (!val.loginName) {
      val.loginName = val.phone;
    }

    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 fields = [
    {
      label: '头像',
      name: 'avatar',
      type: FieldTypes.ImageUploader,
      extra: '建议图片尺寸：320*320px，比例1:1,格式：jpg，用于置业顾问头像,限制大小：100k',
      value: userData.avatar,
      beforeUpload: e => photoBeforeUpload(e),
      // rules: [{ required: true, message: '请选择头像' }],
    },

    {
      label: '工号',
      name: 'jobNumber',
      type: FieldTypes.Text,
      value: userData.jobNumber,
      rules: [{ required: true, message: '请输入工号' }],
    },
    {
      label: '姓名',
      name: 'userName',
      type: FieldTypes.Text,
      value: userData.userName,
      rules: [{ required: true, message: '请输入姓名' }],
    },
    {
      label: '登录名',
      name: 'loginName',
      type: FieldTypes.Text,
      placeholder: '请输入登录名',
      hidden: () => isConsultant,
      value: userData.loginName,
    },
    {
      label: '电话',
      name: 'phone',
      type: FieldTypes.Text,
      placeholder: '请输入电话号码',
      value: userData.phone,
      rules: [
        {
          required: true,
          pattern: new RegExp('^1[0-9]{10}$'),
          message: '请输入正确的电话号码',
        },
      ],
      help: '登录账号为手机号  默认密码：123456',
    },

    {
      label: '是否置业顾问',
      name: 'isConsultant',
      type: FieldTypes.Switch,
      value: userData.isConsultant,
      props: {
        // disabled: userData.isConsultant,
        onChange: e => {
          console.log(e, '------');
          setIsConsultant(e);
        },
      },
    },
    {
      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: 'roleIds',
      render: (
        <Select mode="multiple" style={{ width: '100%' }} placeholder="请选择标签">
          {roleData.map(item => (
            <Select.Option key={item.roleId} value={item.roleId}>
              {item.roleName}
            </Select.Option>
          ))}
        </Select>
      ),
      value: userData.roleIds,
    },
    {
      label: '组织机构',
      name: 'institutionIdLis',
      render: <InstitutionSelect multiple />,
      value: userData.institutionIdLis,
      rules: [{ required: true, message: '组织机构' }],
    },
    {
      label: '授权项目',
      name: 'buildingId',
      render: <BuildingSelection userData={userData} />,
      value: userData.buildingId,
      hidden: () => !isConsultant,
      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: () => isConsultant,
      // rules: [{ required: true, message: '请选择授权项目' }],
    },
    {
      label: '简介',
      name: 'description',
      render: <TextArea rows={7}></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.filter(Boolean)}
        onCancel={() => router.go(-1)}
      ></XForm>
    </Card>
  );
};

export default StaffEdit;
