import React, { useEffect, useState, useMemo } from 'react';
import { Modal, Form, Input, Space, Button, Radio, Select, Spin } from 'antd';

import { dispatch } from '../../../../model';
import { showMessage } from '../../../../util';
import SelectUser from '../../Model/Component/SelectUsers';

// const resourceTypes = [
//   // { key: 'innerSource', name: '内部资源' },
//   // { key: 'outerSource', name: '外部资源' },
//   { key: 'dataAsset', name: '资产' },
//   { key: 'custom', name: '自定义' },
// ]

const CodeInput = ({ value = '', onChange, restrict = false, action }) => {

  const onCodeChange = (e) => {
    if (!restrict || (
      restrict&&(e.target.value===''||/^[A-Z]+$/.test(e.target.value))
    )) {
      onChange?.(e.target.value);
    }
  }

  return <Input 
    placeholder="请输入编号(只允许输入大写英文字母,并且最多3个)" 
    disabled={action!=='add'} 
    maxLength={restrict?3:null} 
    value={value}
    onChange={onCodeChange}
  />
}

const UpdateDirectoryModal = (props) => {

  const { visible, onCancel, dirId, action } = props;

  const [loading, setLoading] = useState(false);
  const [ form ] = Form.useForm();
  const [ dir, setDir ] = useState(null);
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [ isThemeAdd, setIsThemeAdd ] = useState(false);
  const [ users, setUsers ] = useState([]);
  const [ loadingUsers, setLoadingUsers ] = useState(false);

  useEffect(() => {
    if (visible) {
      getUsers();
      if (dirId) {
        getDirectory();
      }
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ visible ])

  const codeRestrict = useMemo(() => {
    if (action === 'add') {
      if (isThemeAdd) return true;

      return (dir && dir.level === 1) ? true : false;
    } else {
      return (dir && dir.level <= 2) ? true : false;
    }

    return false;
  }, [action, dir, isThemeAdd])

  const responsibilityer = React.useMemo(() => {
    if (dir?.responsibilityer) {
      const user = users?.filter((user)=>(user.pernr===dir?.responsibilityer))
      if ((user??[]).length > 0) {
        return user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr;
      }
    }

    return ''
  }, [dir, users]) 

  const marginBottom = useMemo(() => {
    return (action === 'detail') ? 5 : 15
  }, [action])

  const getUsers = () => {
    setLoadingUsers(true);
    dispatch({
      type: 'pds.getOwners',
      callback: (data) => {
        setLoadingUsers(false);
        setUsers(data);
      },
      error: () => {
        setLoadingUsers(false);
      }
    })
  }

  const getDirectory = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.getDirectoryById',
      payload: { 
        dirId
      },
      callback: data => {
        setLoading(false);
        setDir(data);

        if (action !== 'add') {
          form.setFieldsValue(data)
        }
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const onOk = async () => {
    try {
      const row = await form.validateFields();
      
      setConfirmLoading(true);
      
      let payload = {
        data: { 
          ...row,
          resourceType: 'dataAsset',
        }
      };

      if (action === 'add') {
        if (row.type === 'directory') {

          if (dir === null) {
            showMessage('warn', '资产目录的目录节点信息正在加载中...');
            return;
          }
          
          payload = { ...payload, params: {
            parentPath: dir.path||'' 
          }};
        } else {
          payload.data.resourceType = 'dataAsset';
        }
      } else {

        if (dir === null) {
          showMessage('warn', '资产目录的目录节点信息正在加载中...');
          return;
        }

        payload.data = { ...payload.data, ...{ order: dir.order, id: dirId } };
        if (dir.level === 3) {
          payload.data = { ...payload.data, code: dir.code };
        }

        const parentPath = dir.path.substring(0, dir.path.lastIndexOf("/"));;
        payload = { ...payload, params: {
          parentPath
        }};
      }

      dispatch({
        type: 'assetmanage.addOrUpdateDirectory',
        payload: payload,
        callback: data => {
          setConfirmLoading(false);
          reset();
          onCancel && onCancel(true, data?.id||'');
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  const reset = () => {
    form?.resetFields();
    setIsThemeAdd(false);
    setLoading(false);
    setConfirmLoading(false);
    setDir();
  }

  const onReset = () => {
    if(action === 'add') {
      setIsThemeAdd(false);
      form.resetFields();
    } else {
      if (dir === null) {
        showMessage('warn', '资产目录的目录节点信息正在加载中...');
        return;
      }

      form.setFieldsValue({ code: dir?.code, name: dir?.name||'', desc: dir?.desc||'', remarks: dir?.remarks||'' });
    }
  }

  const onValuesChange = (changedValues, allValues) => {
    if (action==='add') {
      if (changedValues.type === 'theme') {
        setIsThemeAdd(true); 
        // if (allValues.code?.length > 3 || !(/^[A-Z]+$/.test(allValues.code))) {
        //   form.setFieldsValue({ code: '' });
        // }
      } else if (changedValues.type === 'directory') {
        setIsThemeAdd(false);
      }
    }
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
    },
  };

  return (
    <Modal
      destroyOnClose
      title='资产目录的目录信息'
      visible={visible}
      width={600}
      onCancel={() => { 
        reset();
        onCancel && onCancel(); 
      }}
      footer={
        (action==='detail') ? null : <Space>
          <Button type="primary" onClick={onOk} loading={confirmLoading}>提交</Button>
          <Button onClick={onReset} >重置</Button>
          <Button onClick={() => {
            reset();
            onCancel && onCancel();
          }}>返回</Button>
        </Space>
      }
    >
      <Spin spinning={loading}>
        <Form {...formItemLayout} form={form} onValuesChange={onValuesChange}>
          {
            action==='add' && <Form.Item 
              label="类型"
              name="type"
              rules={[{ required: true, message: '必填项' }]}
              style={{ marginBottom }}
            >
              <Radio.Group>
                <Radio value='theme'>栏目</Radio>
                <Radio value='directory' disabled={ !dirId }>目录</Radio>
              </Radio.Group>
            </Form.Item>
          }
          {
            codeRestrict && <Form.Item 
              label="编号"
              name="code"
              rules={[{ required: true, message: '必填项' }]}
              style={{ marginBottom }}
            >
              {
                (action==='detail') ? <span>{dir?.code}</span> : <CodeInput restrict={codeRestrict} action={action} />
              }
            </Form.Item>
          }
          <Form.Item 
            label="名称"
            name="name"
            rules={[{ required: true, message: '必填项' }]}
            style={{ marginBottom }}
          >
            {
              (action==='detail') ? <span>{dir?.name}</span> : <Input placeholder="请输入名称" />
            }
          </Form.Item>
          {
            action !== 'add' && (
              <Form.Item
                label="路径"
                name="path"
                style={{ marginBottom }}
              >
                <span>{dir?.path}</span>
              </Form.Item>
            )
          }
          <Form.Item 
            label="描述"
            name="desc"
            style={{ marginBottom }}
          >
            {
              (action==='detail') ? <span>{dir?.desc}</span> : <Input.TextArea placeholder="请输入描述" autoSize={{ minRows: 4, maxRows: 4 }} />
            }
          </Form.Item>
          <Form.Item 
            label="备注"
            name="remarks"
            style={{ marginBottom }}
          >
            {
              (action==='detail') ? <span>{dir?.remarks}</span> : <Input.TextArea placeholder="请输入备注" autoSize={{ minRows: 4, maxRows: 4 }} />
            }
          </Form.Item>
          <Form.Item 
            label="目录负责人"
            name="responsibilityer"
            style={{ marginBottom }}
          >
            {
              (action==='detail') ? <span>{responsibilityer}</span> : <SelectUser 
                type='edit' 
                loading={loadingUsers}
                users={users} 
              />
            }
          </Form.Item>
        </Form>
      </Spin>  
    </Modal>
  );
}

export default UpdateDirectoryModal;