/* 故障报修
 * @Author: Li Hanlin
 * @Date: 2022-12-02 11:41:03
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2023-02-10 17:58:21
 */

import * as React from 'react';
import { useState, useMemo, 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 Addform from '@/components/Addform';
import Detail from '@/components/RepaireDetail/Detail';

function Failure(props) {
  let actionRef = useRef(),
    formRef = useRef();
  const [drawer, setdrawer] = useState({
      open: false,
    }),
    [activeTabKey, setactiveTabKey] = useState('1');

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, params) => {
      if (res?.code == '0000') {
        actionRef?.current?.reload();
        setdrawer((s) => ({
          ...s,
          open: false,
        }));
      }
    },
  });

  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) => {
    if (row?.status == 1) {
      return (
        <PremButton
          pop={{
            title: '是否删除?',
            okText: '确认',
            cancelText: '取消',
            onConfirm: () => {
              run({ url: pathconfig?.delete || '/delete', params: { id: row?.id } });
            },
          }}
          btn={{
            size: 'small',
            type: 'danger',
          }}
        >
          删除
        </PremButton>
      );
    } else {
      return <></>;
    }
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.columns;
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    if (activeTabKey == 1) {
      return defcolumn.concat({
        title: '操作',
        valueType: 'option',
        width: 150,
        render: (text, row, _, action) => [
          defpath?.enableedit && edit(text, row, _, action),
          defpath?.enabledelete && remove(text, row, _, action),
        ],
      });
    } else {
      return defcolumn;
    }
  }, [activeTabKey]);

  const basecolumns = useMemo(() => {
    if (activeTabKey == 1) {
      return [
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '工单状态',
          dataIndex: 'statusName',
          key: 'statusName',
        },
        {
          title: '维修单号',
          dataIndex: 'repairOrderNo',
          key: 'repairOrderNo',
        },
      ];
    } else {
      return [
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '工单状态',
          dataIndex: 'statusName',
          key: 'statusName',
        },
        {
          title: '维修单号',
          dataIndex: 'repairOrderNo',
          key: 'repairOrderNo',
        },
        {
          title: '关单时间',
          dataIndex: 'repairCloseTime',
          key: 'repairCloseTime',
        },
      ];
    }
  }, [activeTabKey]);

  const pathconfig = useMemo(() => {
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    return defpath;
  }, [activeTabKey]);

  const selectType = (type) => {
    switch (type) {
      case 'add':
        return (
          <Addform
            url="/repair/umFailureRepair/save"
            actionRef={actionRef}
            setdrawer={setdrawer}
            drawer={drawer}
          />
        );
      case 'detail':
        return (
          <Detail
            title="报修单号"
            titleno={drawer?.item.repairNo}
            detailpath="/repair/umFailureRepair/queryById"
            params={{ id: drawer?.item.id }}
            baseRow={drawer?.item}
            basecolumns={basecolumns}
            type="gzbx"
          />
        );
      default:
        break;
    }
  };
  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">故障报修</h3>}
        columns={columns}
        path={pathconfig?.list}
        actionRef={actionRef}
        pageextra={pathconfig?.enableadd ? 'add' : null}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          name: '设备报修',
          btn: {
            disabled: false,
            type: 'primary',
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: { isShutdown: 1 },
                title: '设备报修',
                val: 'only',
                type: 'add',
              }));
            },
          },
        }}
        tabList={getcolumns()}
        activeTabKey={activeTabKey}
        onTabChange={(key) => {
          setactiveTabKey(key);
        }}
      />

      <DrawerPro
        fields={columns}
        detailpath={pathconfig?.detail || null}
        detailData={drawer?.item}
        defaultFormValue={drawer?.item}
        params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        {...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 Failure;
