/* 故障设置
 * @Author: Li Hanlin
 * @Date: 2022-12-07 11:19:30
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-30 13:56:38
 */

import * as React from 'react';
import { useState, useMemo, useEffect, useRef } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
import InitForm from '@/components/InitForm';
import { ProDescriptions } from '@ant-design/pro-components';
import { message } from 'antd';
const pathconfig = {
  enableadd: true,
  enableedit: true,
  enabledelete: true,
  enabledetail: true,
  add: '/repair/umFaultSetting/save',
  edit: '/repair/umFaultSetting/save',
  list: '/repair/umFaultSetting/queryList',
  delete: '/repair/umFaultSetting/deleteById',
  detail: '',
};

function Fault(props) {
  const actionRef = useRef(),
    formRef = useRef();
  const [drawer, setdrawer] = useState({
    open: false,
  });
  const [drawergz, setdrawergz] = useState({
    open: false,
  });
  const { run, loading } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, params) => {
      if (res?.code == '0000') {
        actionRef?.current?.reload();
        setdrawer((s) => ({
          ...s,
          open: false,
        }));
      }
    },
  });

  const gzmc = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '详情',
              val: 'only',
              type: 'gzmc',
              title: '详细信息',
            }));
          },
        }}
      >
        故障名称
      </PremButton>
    );
  };

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '编辑',
              val: 'edit',
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: () => {
            run({ url: pathconfig?.delete || '/delete', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setdrawer);
    if (drawer?.type == 'gzmc') {
      return defcolumn;
    } else {
      return defcolumn.concat({
        title: '操作',
        valueType: 'option',
        width: 150,
        render: (text, row, _, action) => [
          pathconfig?.enabledetail && gzmc(text, row, _, action),
          pathconfig?.enableedit && edit(text, row, _, action),
          pathconfig?.enabledelete && remove(text, row, _, action),
        ],
      });
    }
  }, [drawer?.type]);

  const FaultName = (props) => {
    const [request, setrequest] = useState();
    const gzmcref = useRef();
    const remove = (text, row, _, action) => {
      return (
        <PremButton
          pop={{
            title: '是否删除?',
            okText: '确认',
            cancelText: '取消',
            onConfirm: async () => {
              let res = await doFetch({
                url: '/repair/umFaultSettingDetail/deleteById',
                params: { id: row.id },
              });
              if (res.code === '0000') {
                message.success('删除成功！');
                setdrawergz((s) => ({
                  ...s,
                  open: false,
                }));
                actionRef.current.reload();
              }
            },
          }}
          btn={{
            size: 'small',
            type: 'danger',
          }}
        >
          删除
        </PremButton>
      );
    };
    const edit = (text, row, _, action) => {
      return (
        <PremButton
          btn={{
            size: 'small',
            onClick: () => {
              setdrawergz((s) => ({
                ...s,
                open: true,
                title: '编辑',
                val: 'edit',
                detailpath: '/repair/umFaultSettingDetail/queryById',
                params: { id: row.id },
                onFinish: async (vals) => {
                  //console.log(1);
                  let params = {
                    ...vals,
                    faultSettingId: drawer?.item.id,
                    id: row.id,
                  };
                  let res = await doFetch({
                    url: '/repair/umFaultSettingDetail/save',
                    params,
                  });
                  if (res.code === '0000') {
                    message.success('编辑成功！');
                    setdrawergz((s) => ({
                      ...s,
                      open: false,
                    }));
                    actionRef.current.reload();
                  }
                },
              }));
            },
          }}
        >
          编辑
        </PremButton>
      );
    };

    const columns = useMemo(() => {
      return [
        {
          title: '故障名称',
          dataIndex: 'faultDetailName',
          key: 'faultDetailName',
          formItemProps: {
            rules: [
              {
                required: true,
                message: '此项为必填项',
              },
            ],
          },
        },
        {
          title: '故障名称代码',
          dataIndex: 'faultDetailCode',
          key: 'faultDetailCode',
        },
        {
          title: '故障描述',
          dataIndex: 'faultPhenomenon',
          key: 'faultPhenomenon',
          valueType: 'textarea',
        },
        {
          title: '解决方案',
          dataIndex: 'faultSolution',
          key: 'faultSolution',
          valueType: 'textarea',
          search: false,
        },
        {
          title: '操作',
          valueType: 'option',
          width: 150,
          render: (text, row, _, action) => [
            edit(text, row, _, action),
            remove(text, row, _, action),
          ],
        },
      ];
    }, []);
    const renderRef = useRef(true);

    return (
      <>
        <ProDescriptions
          dataSource={drawer?.item}
          columns={[
            {
              title: '故障类型',
              dataIndex: 'faultType',
              key: 'faultType',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '故障类型代码',
              dataIndex: 'faultCode',
              key: 'faultCode',
            },
            {
              title: '设备类型',
              dataIndex: 'equipmentTypeName',
              key: 'equipmentTypeId',
            },
          ]}
        />
        <AutoTable
          columns={columns}
          formRef={gzmcref}
          path="/repair/umFaultSettingDetail/queryList"
          extraparams={{ faultSettingId: drawer?.item.id }}
          pageextra={'add'}
          resizeable={false}
          addconfig={{
            // access: 'sysDepartment_save',
            btn: {
              disabled: false,
              type: 'primary',
              onClick: () => {
                setdrawergz((s) => ({
                  ...s,
                  open: true,
                  title: '新建故障名称',
                  val: 'add',
                  onFinish: async (vals) => {
                    let params = {
                      ...vals,
                      faultSettingId: drawer?.item.id,
                    };
                    let res = await doFetch({
                      url: '/repair/umFaultSettingDetail/save',
                      params,
                    });
                    if (res.code === '0000') {
                      message.success('新增成功！');
                      setdrawergz((s) => ({
                        ...s,
                        open: false,
                      }));
                      gzmcref.current.reload();
                    }
                  },
                }));
              },
            },
          }}
        />
        <DrawerPro
          placement="right"
          fields={columns}
          actionRef={gzmcref}
          style={{ transform: 'translateX(180px)' }}
          defaultFormValue={drawergz?.item}
          onClose={() => {
            setdrawergz((s) => ({
              ...s,
              open: false,
              type: null,
              item: null,
            }));
          }}
          {...drawergz}
        />
      </>
    );
  };

  function selectType(type) {
    switch (type) {
      case 'gzmc':
        return <FaultName />;
      default:
        break;
    }
  }
  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">故障设置</h3>}
        columns={columns}
        actionRef={actionRef}
        path={pathconfig?.list || '/ngic-auth/sysUser/query/page'}
        pageextra={pathconfig?.enableadd ? 'add' : null}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            disabled: false,
            type: 'primary',
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: null,
                title: '新增',
                val: 'add',
              }));
            },
          },
        }}
      />

      <DrawerPro
        fields={columns}
        // params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        // detailpath={pathconfig?.detail || null}
        detailData={drawer?.item}
        defaultFormValue={drawer?.item}
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
            type: null,
            item: null,
          }));
        }}
        {...drawer}
        onFinish={(vals) => {
          if (drawer?.val == 'add') {
            run({ url: pathconfig?.add || '/add', params: { ...vals } });
          } else if (drawer?.val == 'edit') {
            run({ url: pathconfig?.edit || '/edit', params: { ...vals, id: drawer?.item?.id } });
          }
        }}
      >
        {selectType(drawer?.type)}
      </DrawerPro>
    </div>
  );
}

export default Fault;
