/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-11-25 10:49:44
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /TracerMethodology_PC/src/pages/UserMana/index.js
 */

import { PlusOutlined } from '@ant-design/icons';
import { Button, Popconfirm,Tooltip} from 'antd';
import React, { useState, useRef } from 'react';

import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormSelect, ProFormDigit,ProFormDependency } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
import { addList, editList, delList } from './service';
import { InfoCircleOutlined } from '@ant-design/icons';
import { getMenuList } from '@/pages/PlatformMana/menuManage/service';

const UserMana = () => {
  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
      width:'20%'
      // ellipsis: true,
    },
    {
      title: '菜单Id',
      dataIndex: 'menuId',
      key: 'menuId',
      hideInSearch: true,
    },
    {
      title: 'URL',
      dataIndex: 'url',
      key: 'url',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: 'Path',
      dataIndex: 'path',
      key: 'path',
      ellipsis: true,
      hideInSearch: true,
      width:'20%'
    },
    {
      title: '变更人',
      dataIndex: 'modifyUserName',
      key: 'modifyUserName',
      hideInSearch: true,

    },
    {
      title: '变更日期',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        const { type } = record;
        const btnGroups = [
          <a
            key="config"
            onClick={() => {
              handleUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            编辑
          </a>,
          <Popconfirm
            key="subscribeAlert"
            title="是否确定删除?"
            onConfirm={() => {
              delUserHandler(record);
            }}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
        return type != 0
          ? [...btnGroups]
          : [
              <a
                key="config"
                onClick={() => {
                  setIfAddZeroLevelMenu(false);
                  handleModalVisible(true);
                  setCurrentRow(record);
                }}
              >
                添加
              </a>,
              ...btnGroups,
            ];
      },
    },
  ];

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState(undefined);
  const [ifAddZeroLevelMenu, setIfAddZeroLevelMenu] = useState(true);

  // const [shareParamsSetting,setShareParamsSetting] = useState(false);  //是否分摊参数设置

  /**
   *
   * @param {Boolean} bool 弹窗展示状态
   */
  const updateModalVisibleChange = (bool) => {
    handleUpdateModalVisible(bool);
    if (!bool) setCurrentRow(undefined);
  };

  // 获取Drawer菜单列表
  const getMenus = async (params = {}, sort, filter) => {
    const res = await getMenuList(params);
    if(res){
      return {
        data: res.list,
        total: res.totalCount,
        success:true,
      };
    }
  };

  /**
   *
   * @param {Object} value 删除项数据
   */
  const delUserHandler = async (value) => {
    const ids = [value.menuId];
    const resp = await delList({ ids });
    if (resp) {
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getMenus}
        actionRef={actionRef}
        rowKey="menuId"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setIfAddZeroLevelMenu(true);
              handleModalVisible(true);
            }}
          >
            新增
          </Button>,
        ]}
        pagination={{
          pageSize: 10,
        }}
        search={false}
      />

      <ModalForm
        title="新增菜单"
        width="800px"
        labelCol={{ span: 5, offset: 3 }}
        layout={'horizontal'}
        modalProps={{
          destroyOnClose: true,
        }}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          let id = 0;
          currentRow && (id = currentRow.menuId);
          // console.log({id});
          const resp = await addList({ ...value, parentId: id });
          if (resp) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
            return true;
          }
          setCurrentRow(undefined);
        }}
      >
        <ProFormText
          label="菜单名称"
          rules={[
            {
              required: true,
              message: '角色名是必填项！',
            },
          ]}
          width="sm"
          name="name"
          placeholder="请输入菜单"
        />
        <ProFormText
          label="Path"
          rules={[
            {
              required: true,
              message: '菜单路径是必填项！',
            },
          ]}
          width="sm"
          name="path"
        />
        {/* <ProFormText
          label="权限字段"
          rules={[
            {
              required: true,
              message: '权限字段是必填项！',
            },
          ]}
          width="sm"
          name="perms"
          placeholder="请输入"
        /> */}
        <ProFormSelect
          name="type"
          label="类型"
          width="sm"
          options={[
            { label: '目录', value: 0 },
            { label: '菜单', value: 1 },
            { label: '按钮', value: 2 },
          ]}
          fieldProps={{
            optionItemRender(item) {
              return `${item.label  } - ${  item.value}`;
            },
          }}
          placeholder="请选择类型"
          rules={[{ required: true, message: '请选择类型!' }]}
        />
        <ProFormText
          label="菜单Icon"
          rules={[
            {
              required: false,
            },
          ]}
          width="sm"
          name="icon"
        />
        <ProFormDigit
          label="菜单排序"
          rules={[
            {
              required: false,
            },
          ]}
          width="sm"
          name="orderNum"
          placeholder="请选择菜单序号"
        />
        <ProFormDependency name={['type']}>
            {
               ({type})=>{
                if(type == 1){
                  return (
                    <ProFormText
                      label="帆软url"
                      rules={[
                        {
                          required: false,
                        },
                      ]}
                      fieldProps={{
                        suffix:<Tooltip title="注意，填写该地址，页面内容将被代理!">
                        <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)' }} />
                      </Tooltip>
                      }}
                      width="sm"
                      name="softUrl"
                    />
                  )
               }
            }
          }
        </ProFormDependency>
      </ModalForm>

      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          const { menuId, parentId = 0 } = currentRow;
          // console.log({currentRow});
          // console.log({'编辑':value});
          const { name, path, url, perms, type, icon = 'ww', orderNum,softUrl } = value;

          const resp = await editList({
            parentId,
            name,
            path,
            url,
            perms,
            type,
            icon,
            orderNum,
            id: menuId,
            softUrl
          });
          if (resp) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        updateModalVisibleChange={updateModalVisibleChange}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default UserMana;
