/* 扩展字段
 * @Author: Li Hanlin
 * @Date: 2022-11-10 09:39:56
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-19 11:25:53
 */

import * as React from 'react';
import { useState, useMemo, useRef, useEffect } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { doFetch } from '@/utils/doFetch';
import { message, Dropdown, Menu, Layout, Button, Image, Space, Divider, Tabs } from 'antd';
import TreeRender from '@/components/TreeRender';
import { ProDescriptions } from '@ant-design/pro-components';
import InitForm from '@/components/InitForm';

const { Sider, Content } = Layout;

function Field(props) {
  const actionRef = useRef(),
    formRef = useRef(),
    [drawer, setDrawer] = useState({
      visible: false,
    }),
    [items, setitems] = useState([]),
    [extraparams, setextraparams] = useState({}),
    urlParams = {
      save: '/base/paFormField/save',
      remove: '/base/paFormField/delete',
      list: '/base/paFormField/queryPage',
      detail: '/asset/equipment/detail',
      formList: '/base/paForm/queryList',
    };

  useEffect(() => {
    const fn = async () => {
      const result = await doFetch({
        url: urlParams.formList,
        params: {},
      });
      //console.log(result);
      if (!result?.data?.dataList.length == 0) {
        setitems(
          result?.data?.dataList.map((it, index) => {
            return {
              key: it.id,
              label: it.formName,
            };
          }),
        );
        setDrawer((s) => ({
          ...s,
          formName: result?.data?.dataList[0]?.formName,
          formId: result?.data?.dataList[0]?.id,
        }));
      }
    };
    fn();
  }, []);

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              title: '编辑',
              fields: getcolumns(true),
              val: 'edit',
              // detailpath: urlParams.detail,
              // params: { id: row.id },
              item: {
                ...row,
                fieldChar: String(row?.fieldChar),
                formName: drawer?.formName,
                formId: drawer?.formId,
              },
              onFinish: async (vals) => {
                //console.log(vals);
                let params = {
                  ...vals,
                  id: row.id,
                  formId: drawer?.formId,
                };
                delete params.formName;
                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);

    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, row, _, action) => [edit(text, row, _, action), remove(text, row, _, action)],
    });
  }, []);

  return (
    <div style={{ position: 'relative' }}>
      <div className="ant-card-head">
        <div className="ant-card-head-wrapper">
          <div className="ant-card-head-title">
            <h3 className="page-title">扩展字段</h3>
          </div>
        </div>
      </div>
      <Layout style={{ height: '100%' }}>
        <Sider theme="light" width={300}>
          <div>
            <h3
              style={{
                paddingLeft: 24,
                paddingRight: 24,
                paddingTop: 24,
                paddingBottom: 8,
              }}
            >
              表单信息
            </h3>
            <Menu
              onClick={async (e) => {
                // //console.log(e);
                setextraparams({
                  formId: e?.key,
                });
                setDrawer((s) => ({
                  ...s,
                  formName: items.filter((it) => it?.key == e?.key)[0].label,
                  formId: e?.key,
                }));
              }}
              style={{
                width: '100%',
              }}
              defaultSelectedKeys={['1']}
              mode="inline"
              items={items}
            />
          </div>
        </Sider>
        <Content>
          <AutoTable
            pagetitle={<h3 style={{ marginBottom: 0, fontWeight: 400 }}>字段信息</h3>}
            columns={columns}
            path={urlParams.list}
            params={{ formId: '1' }}
            actionRef={actionRef}
            pageextra={'add'}
            resizeable={false}
            addconfig={{
              // access: 'sysDepartment_save',
              btn: {
                disabled: false,
                type: 'primary',
                onClick: () => {
                  //console.log(drawer);
                  setDrawer((s) => ({
                    ...s,
                    visible: true,
                    item: {
                      fieldChar: '1',
                      formName: drawer?.formName,
                      formId: drawer?.formId,
                    },
                    title: '新增',
                    val: 'add',
                    fields: getcolumns(false),
                    onFinish: async (vals) => {
                      //console.log(vals);
                      let params = {
                        ...vals,
                        formId: drawer?.formId,
                      };
                      delete params.formName;
                      let res = await doFetch({
                        url: urlParams.save,
                        params,
                      });
                      if (res.code === '0000') {
                        message.success('新增成功！');
                        setDrawer((s) => ({
                          ...s,
                          visible: false,
                        }));
                        actionRef.current.reload();
                      }
                    },
                  }));
                },
              },
            }}
            // x={1500}
            extraparams={extraparams}
          />
        </Content>
      </Layout>
      <DrawerPro
        fields={columns}
        formRef={formRef}
        defaultFormValue={drawer?.item ?? {}}
        placement="right"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            visible: false,
            item: null,
            detailpath: null,
            params: null,
          }));
        }}
        {...drawer}
      />
    </div>
  );
}

export default Field;
