/* 用户管理
 * @Author: Li Hanlin
 * @Date: 2022-11-09 14:44:44
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2023-02-10 17:54:56
 */

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: { currentUser }, loading, error, refresh, setInitialState } = useModel('@@initialState');
  const [username, setusername] = useState(null),
    [fieldColumns, cfc] = useState([]);

  let 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: () => {
            doFetch({ url: urlParams.detail, params: { id: row.id } }).then(res => {
              if (res.code == '0000') {
                let data = res?.data?.data ?? {};
                setDrawer((s) => ({
                  ...s,
                  visible: true,
                  item: { ...data, usernamefullname: `${data?.username}-${data?.fullName}` },
                  type: 'edit',
                  title: '编辑',
                  val: 'only'
                }));
              }
            })

          },
        }}
      >
        编辑
      </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, currentUser?.isLease);
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [edit(text, row, _, action), remove(text, row, _, action)],
    });
  }, [currentUser?.isLease]);
  useEffect(() => {
    if (drawer.type == 'add') {
      cfc(getcolumns(setDrawer, false, formRef, currentUser?.isLease))
    } else if (drawer.type == 'edit') {
      cfc(getcolumns(setDrawer, true, formRef, currentUser?.isLease))
    }
  }, [drawer.type]);
  const valuechange = (changedValues, allValues) => {
    for (let i in changedValues) {
      if (i == "factoryIdList" || i == 'shopIdList' || i == "sectionIdList" || i == "productionLineIdList") {
        let changeFiefls = fieldColumns?.filter(it => it.key == i)?.[0];
        let newValindex = changedValues[i]?.indexOf('all'), oldValindex = drawer.item[i]?.indexOf('all') ?? -1, newObj = [];
        if (newValindex != -1 && oldValindex == -1 && changedValues[i].length > 1) {
          newObj = ['all'];
        } else if (newValindex != -1 && oldValindex != -1 && changedValues[i].length > 1) {
          newObj = changedValues[i].filter(it => it != 'all');
        } else if (newValindex != -1 && oldValindex == -1 && changedValues[i].length == 1) {
          newObj = ['all'];
        } else {
          newObj = changedValues[i]
        }
        formRef?.current?.setFieldsValue({ [i]: newObj });
        setDrawer((s) => {
          return {
            ...s,
            item: { ...drawer.item, ...{ [i]: newObj } }
          }
        });
      }
    }

  }
  function selectType(type) {
    switch (type) {
      case 'add':
        return (
          fieldColumns?.length && <ExtendField
            setDrawer={setDrawer}
            drawer={drawer}
            formRef={formRef}
            columns={fieldColumns}
            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?.usernamefullname.slice(0, vals?.usernamefullname?.indexOf('-')),
                id: drawer?.title == '编辑' ? drawer?.item?.id : '',
                userCharReqList,
              };
              delete params.usernamefullname;
              delete params.shopId;
              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={valuechange}
          />
        );

      case 'edit':
        return (
          fieldColumns?.length && <ExtendField
            setDrawer={setDrawer}
            drawer={drawer}
            actionRef={actionRef}
            columns={fieldColumns}
            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?.usernamefullname.slice(0, vals?.usernamefullname?.indexOf('-')),
                id: drawer?.title == '编辑' ? drawer?.item?.id : '',
                userCharReqList,
              };
              delete params.shopId;
              delete params.usernamefullname;
              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();
              }
            }}
            formRef={formRef}
            onValuesChange={valuechange}
            defaultFormValue={drawer.item}
          />
        );
        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;
