/* 用户管理
 * @Author: Li Hanlin
 * @Date: 2022-11-09 14:44:44
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-19 10:32:30
 */

import * as React from 'react';
import { useState, useMemo, useRef, useEffect, useCallback } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import InitForm from '@/components/InitForm';
import getcolumns from './columns';
import { doFetch } from '@/utils/doFetch';
import { message, AutoComplete } from 'antd';
import ExtendField from '@/components/ExtendField';
import { useModel } from 'umi';
import { useRequest } from 'ahooks';
import { indexOf } from 'lodash';

function User(props) {
  const { initialState, loading, error, refresh, setInitialState } = useModel('@@initialState');
  const [username, setusername] = useState(null);

  const actionRef = useRef(),
    formRef = useRef();
  const [drawer, setDrawer] = useState({
    visible: false,
  });

  const urlParams = {
    save: '/auth/sysUser/save',
    remove: '/auth/sysUser/deleteById',
    list: '/auth/sysUser/queryList',
    detail: '/auth/sysUser/detail',
  };

  const detail = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          type: 'link',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              // item: row,
              title: '详情',
              val: 'detail',
              title: row.userName + '的详细信息',
            }));
          },
        }}
      >
        详情
      </PremButton>
    );
  };

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              item: row,
              type: 'edit',
              title: '编辑',
              val: 'only',
              // onFinish: async (vals) => {
              //   let userCharReqList = [];
              //   //console.log('id:', row.id);
              //   for (let i in vals) {
              //     if (!isNaN(Number(i))) {
              //       userCharReqList.push({
              //         fieldId: i,
              //         fieldRealValue: vals[i],
              //       });
              //       delete vals[i];
              //     }
              //   }
              //   let params = {
              //     ...vals,
              //     id: row?.id,
              //     shopIdList: vals.shopId,
              //     userCharReqList,
              //   };
              //   delete params.shopId;
              //   let res = await doFetch({
              //     url: urlParams.save,
              //     params,
              //   });
              //   if (res.code === '0000') {
              //     message.success('编辑成功！');
              //     setDrawer((s) => ({
              //       ...s,
              //       visible: false,
              //     }));
              //     actionRef.current.reload();
              //   }
              // },
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除该用户?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            let res = await doFetch({ url: urlParams.remove, params: { id: row.id } });
            if (res.code === '0000') {
              message.success('删除成功！');
              setDrawer((s) => ({
                ...s,
                visible: false,
              }));
              actionRef.current.reload();
            }
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setDrawer, false, formRef);
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [edit(text, row, _, action), remove(text, row, _, action)],
    });
  }, []);

  function selectType(type) {
    switch (type) {
      case 'add':
        return (
          <ExtendField
            setDrawer={setDrawer}
            drawer={drawer}
            formRef={formRef}
            columns={getcolumns(setDrawer, false, formRef)}
            formId={'1'}
            // urlParams={urlParams}
            onFinish={async (vals) => {
              let userCharReqList = [];
              for (let i in vals) {
                if (!isNaN(Number(i))) {
                  userCharReqList.push({
                    fieldId: i,
                    fieldRealValue: vals[i],
                  });
                  delete vals[i];
                }
              }
              let params = {
                ...vals,
                username: vals?.username.slice(0, vals?.username?.indexOf('-')),
                id: drawer?.title == '编辑' ? drawer?.item?.id : '',
                userCharReqList,
              };
              delete params.shopId;
              //console.log(params, '!!!!');
              let res = await doFetch({
                url: urlParams.save,
                params,
              });
              if (res.code === '0000') {
                if (drawer?.title == '编辑') {
                  message.success('编辑成功！');
                } else {
                  message.success('新增成功！');
                }
                setDrawer((s) => ({
                  ...s,
                  visible: false,
                }));
                actionRef.current.reload();
              }
            }}
            defaultFormValue={drawer.item}
            // onValuesChange={(changedValues, allValues) => {
            //   console.log(changedValues, allValues);
            //   if (changedValues['username']) {
            //     console.log(changedValues, allValues);
            //   }
            // }}
          />
        );

      case 'edit':
        return (
          <ExtendField
            setDrawer={setDrawer}
            drawer={drawer}
            actionRef={actionRef}
            columns={getcolumns(setDrawer, true, formRef)}
            formId={'1'}
            urlParams={urlParams}
            onFinish={async (vals) => {
              let userCharReqList = [];
              for (let i in vals) {
                if (!isNaN(Number(i))) {
                  userCharReqList.push({
                    fieldId: i,
                    fieldRealValue: vals[i],
                  });
                  delete vals[i];
                }
              }
              let params = {
                ...vals,
                id: drawer?.title == '编辑' ? drawer?.item?.id : '',
                userCharReqList,
              };
              delete params.shopId;
              //console.log(params, '!!!!');
              let res = await doFetch({
                url: urlParams.save,
                params,
              });
              if (res.code === '0000') {
                if (drawer?.title == '编辑') {
                  message.success('编辑成功！');
                } else {
                  message.success('新增成功！');
                }
                setDrawer((s) => ({
                  ...s,
                  visible: false,
                }));
                actionRef.current.reload();
              }
            }}
          />
        );
        break;

      default:
        return null;
    }
  }

  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">用户管理</h3>}
        columns={columns}
        path={urlParams.list}
        actionRef={actionRef}
        pageextra={'add'}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            type: 'primary',
            disabled: false,
            onClick: () => {
              // let res = await doFetch({url:})
              setDrawer((s) => ({
                ...s,
                visible: true,
                item: {
                  status: 1,
                },
                detailpath: '',
                params: {},
                title: '新增',
                type: 'add',
                val: 'only',
              }));
            },
          },
        }}
      />

      <DrawerPro
        fields={columns}
        // detailpath={urlParams.detail}
        // params={{ id: drawer?.item?.id }}
        defaultFormValue={drawer?.item ?? {}}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            visible: false,
          }));
        }}
        {...drawer}
      >
        {selectType(drawer?.type)}
      </DrawerPro>
    </div>
  );
}

export default User;
