import React, {
  useState, useEffect, useContext
} from 'react';
import { Form, Input, Select, Button, Switch, TreeSelect, message, Space } from 'antd';
import apiObj from '@api/index';
import { organizationData } from '@utils/index'
import UserContext from './user-context';
import { useSelector } from 'react-redux'
const { post, api, xPost } = apiObj;
const { Option } = Select;

const { SHOW_PARENT } = TreeSelect;
function AddUser(props) {
  useEffect(() => {
    getHospitalTree();
    getCreateRoles()
  }, []);
  const [form] = Form.useForm();
  const { userId, type, formData, roleList } = useContext(UserContext);
  const [treeData, setTreeData] = useState([]);
  const [treeRloe, setTreeRloe] = useState([]);
  const [addHospitalTreeVO, setAddHospitalTreeVO] = useState({
    depts: [],
    hospitals: []
  });
  const staticInfo = useSelector(state => {
    return state.staticInfo;
  });
  const { titleList } = staticInfo;
  const initialValues = formData;
  const hospitalName = formData.hospitalName ? formData.hospitalName.join(","):[]
  let addHospitalTreeVOs = {
    depts: [],
    hospitals: [],
  }
  //获取当前用户组织
  function getHospitalTree() {
    post(api.getHospitalTree).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        const treeData = organizationData(data)
        setTreeData(treeData)
      }
    })
  }
  function addAttr(data) {
    for (var j = 0; j < data.length; j++) {
      data[j].title = data[j].name //添加title属性
      data[j].key = data[j].code //添加key属性
      if (data[j].children.length > 0) {
        addAttr(data[j].children)
      }
    }
    return data
  }
  //获取当前用于所属角色
  function getCreateRoles() {
    const params = {
      softwareId: ''
    }
    xPost(api.getCreateRoles, params).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        let arr = JSON.parse(JSON.stringify(data).replace(/name/g, 'title').replace(/id/g, 'value'))
        setTreeRloe(arr)
      }
    })
  }
  // 去重
  function unique(arr) {
    return arr.filter(function (item, index, arr) {
      return arr.indexOf(item, 0) === index;
    });
  }
  function swichChange(val) {
    form.setFieldsValue({ status: val ? 1 : 0 })
  }
  // 判断元素存在格式
  function getSameNum(val, arr) {
    let processArr = arr.filter(function (value) {
      return value == val;
    })
    return processArr.length;
  }
  //递归获取科室
  function gethospitals(arr, val) {
    arr.forEach(item => {
      if (item.value == val) {
        if (item.children) {
          getdepts(item.children)
        }
        if (item.children && item.depts) {
          item.children.forEach(item => {
            addHospitalTreeVOs.depts.push(item.value.split('-')[1])
          })
        }
      } else {
        if (item.children) {
          gethospitals(item.children, val)
        }
      }
    })
  }
  //递归获取医院
  function getdepts(arr) {
    arr.forEach(item => {
      if (JSON.stringify(item.value).indexOf('-') < 0) {
        addHospitalTreeVOs.hospitals.push(item.value)
      }
      if (item.children && item.depts) {
        item.children.forEach(it => {
          addHospitalTreeVOs.depts.push(it.value.split('-')[1])
        })
        return
      }
      if (item.children) {

        getdepts(item.children)
      }
    })
  }
  const onChange = value => {
    value.forEach(it => {
      if (JSON.stringify(it).indexOf('-') > 0) {
        addHospitalTreeVOs.depts.push(it.split('-')[1])
      } else {
        addHospitalTreeVOs.hospitals.push(it)
        gethospitals(treeData, it)
      }
    })
    setAddHospitalTreeVO(addHospitalTreeVOs)
    console.log(form.getFieldsValue())
  };
  const onChangeRloe = value => {
    form.setFieldsValue({ roles: value })
  };
  const onFinish = values => {
    let params = values
    addHospitalTreeVO.hospitals = unique(addHospitalTreeVO.hospitals)
    params.addHospitalTreeVO = addHospitalTreeVO
    if (type == 2) {
      params.id = userId
      editUser(params)
    } else {
      addUser(params)
    }

  };
  function addUser(param) {
    post(api.addUser, param).then((res) => {
      if (res.data.code === 200) {
        props.userChange()
        message.success(res.data.message);
        form.resetFields();
      } else {
        message.error(res.data.message);
      }
    })
  }
  function editUser(param) {
    post(api.updateUser, param).then((res) => {
      if (res.data.code === 200) {
        props.userChange()
        message.success(res.data.message);
        form.resetFields();
      } else {
        message.error(res.data.message);
      }
    })
  }
  function cancel() {
    props.cancel()
  }

  return (
    <>
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        form={form}
        name="register"
        onFinish={onFinish}
        initialValues={initialValues}
        className='user'
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            {
              required: true,
              message: '请输入用户名',
            },
          ]}
        >
          {type == 3 ?
            <span>{initialValues.username}</span>
            :
            <Input placeholder="用户名是组织中唯一标识，请勿重复" autoComplete='off' />
          }

        </Form.Item>
        <Form.Item
          name="mobilePhone"
          label="手机号码"
          rules={[
            {
              required: true,
              message: '请输入手机号码',
            },
          ]}
        >
          {type == 3 ?
            <span>{initialValues.mobilePhone}</span>
            :
            <Input placeholder="请输入手机号码" autoComplete='off' />
          }

        </Form.Item>
        <Form.Item
          name="password"
          label="初始密码"
          rules={[
            {
              required: true,
              message: '8-12位大小写字母、数字、特殊字符',
            },
            {
              min: 8,
              message: '密码不能少于8个字符',
            }, {
              max: 12,
              message: '密码不能大于12个字符',
            }
          ]}
        >
          {type == 3 ?
            <span>{initialValues.password}</span>
            :
            <Input.Password placeholder="8-12位大小写字母、数字、特殊字符" autoComplete='off' disabled={type == 2 ? true : false} />
          }
        </Form.Item>
        <Form.Item
          name="againpassword"
          label="确认密码"
          dependencies={['password']}
          rules={[
            {
              required: true,
              message: '8-12位大小写字母、数字、特殊字符',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次密码不一致,请确认密码'));
              },
            }),
          ]}
        >
          {type == 3 ?
            <span>{initialValues.password}</span>
            :
            <Input.Password placeholder="8-12位大小写字母、数字、特殊字符" autoComplete='off' disabled={type == 2 ? true : false} />
          }
        </Form.Item>
        <Form.Item
          name="name"
          label="姓名"
          rules={[{ required: true, message: '请输入姓名', whitespace: true }]}
        >
          {type == 3 ?
            <span>{initialValues.name}</span>
            :
            <Input placeholder="请输入姓名" autoComplete='off' />
          }

        </Form.Item>
        <Form.Item
          name="idcard"
          label="身份证号码"
        >
          {type == 3 ?
            <span>{initialValues.idcard}</span>
            :
            <Input placeholder="请输入身份证号码" autoComplete='off' />
          }

        </Form.Item>
        <Form.Item
          name="addHospitalTreeVO"
          label="所属组织"
          rules={[{ required: true, message: '请选择所属组织' }]}
        >

          {type == 3 ?
            <span>{hospitalName}</span>
            :
            <TreeSelect
              showSearch={false}
              treeData={treeData}
              onChange={onChange}
              maxTagCount={1}
              treeCheckable
              showCheckedStrategy={SHOW_PARENT}
              placeholder="请选择"
              style={{ width: '100%' }}
            />
          }

        </Form.Item>
        <Form.Item
          name="titleId"
          label="医疗组"
        >
          {type == 3 ?
            <span>{initialValues.idcard}</span>
            :
            <Select placeholder="请选择">
              {titleList.map((item, i) => {
                return (
                  <Option value={item.name} key={i}>{item.val}</Option>
                )
              })}
            </Select>
          }

        </Form.Item>
        <Form.Item
          name="titleId"
          label="职称"
        >
          {type == 3 ?
            <span>{initialValues.idcard}</span>
            :
            <Select placeholder="请选择职称">
              {titleList.map((item, i) => {
                return (
                  <Option value={item.name} key={i}>{item.val}</Option>
                )
              })}
            </Select>
          }

        </Form.Item>
        <Form.Item
          name="jobNo"
          label="工号"
        >
          {type == 3 ?
            <span>{initialValues.jobNo}</span>
            :
            <Input placeholder="请输入工号" autoComplete='off' />
          }

        </Form.Item>
        <Form.Item
          name="roles"
          label="所属角色"
          rules={[{ required: true, message: '请选择角色' }]}
        >
          {type == 3 ?
            <div>
              {roleList.map((it, i) => {
                return (
                  <span key={i}>{it.roleName}、</span>
                );
              })}
            </div>
            :
            <TreeSelect
              showSearch={false}
              treeData={treeRloe}
              treeCheckable
              onChange={onChangeRloe}
              showCheckedStrategy={SHOW_PARENT}
              placeholder="请选择角色"
              style={{ width: '100%' }}
              disabled={type == 3 ? true : false}
            />
          }
        </Form.Item>
        <Form.Item
          name="orderNo"
          label="排序"
        >
          {type == 3 ?
            <span>{initialValues.orderNo}</span>
            :
            <Input placeholder="大于0的整数" autoComplete='off' />
          }

        </Form.Item>
        <Form.Item
          name="status"
          valuePropName="checked"
          label="当前状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          {type == 3 ?
            <span>{initialValues.status == 1 ? '启用' : '禁用'}</span>
            :
            <Switch onChange={swichChange} />
          }

        </Form.Item>
        {type == 3 ?
          <Form.Item wrapperCol={{ offset: 10, span: 16 }}>
            <Space size="middle">
              <Button type="primary" onClick={e => cancel()}>
                返回
              </Button>
            </Space>
          </Form.Item>
          :
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space size="middle">
              <Button htmlType="button" onClick={e => cancel()}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
            </Space>
          </Form.Item>}

      </Form>
    </>
  );
}

export default AddUser;