/* 维修工单
 * @Author: Li Hanlin
 * @Date: 2022-12-02 11:41:03
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-08 14:35:09
 */

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 { Menu, Dropdown, Button, message } from 'antd';
import InitForm from '@/components/InitForm';

function Failure(props) {
  const actionRef = useRef(),
    containderef = 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 detail = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          type: 'link',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '详情',
              val: 'detail',
              title: '详细信息',
            }));
          },
        }}
      >
        详情
      </PremButton>
    );
  };

  // 完成外协
  const CompleteOuts = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '外协单位',
              dataIndex: 'otherUnitsId',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              key: 'otherUnitsId',
              valueType: 'select',
              options: {
                path: '/asset/equipmentSupplier/query/selection',
                params: {},
              },
            },
            {
              title: '故障原因',
              dataIndex: 'causeFailure',
              valueType: 'textarea',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              key: 'causeFailure',
            },
            {
              title: '维修内容',
              dataIndex: 'repairContent',
              valueType: 'textarea',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              key: 'repairContent',
            },
            {
              title: '外协时长',
              dataIndex: 'otherUnitsHours',
              key: 'otherUnitsHours',
              // valueType: 'number',
            },
            {
              title: '外协费用',
              dataIndex: 'otherUnitsCost',
              key: 'otherUnitsCost',
            },
            {
              title: '备注',
              dataIndex: 'remark',
              key: 'remark',
              valueType: 'textarea',
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              otherUnitsFinish: vals,
              id: drawer?.item?.id,
            };
            let res = await doFetch({
              url: '/repair/umOtherUnitsOrder/finishOtherUnits',
              params,
            });
            if (res.code === '0000') {
              message.success('成功完成外协！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
        />
      </>
    );
  };

  // 重新指派
  const Reassig = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '最新外协人员',
              dataIndex: 'newRepairUserName',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              fieldProps: { disabled: true },
              key: 'newRepairUserName',
            },
            {
              title: '外协人员',
              dataIndex: 'otherUnitsAssistList',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              key: 'otherUnitsAssistList',
              valueType: 'select',
              options: {
                path: '/repair/umOtherUnitsOrder/selectionAgain',
                params: { id: drawer?.item.id },
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              otherUnitsAssistList: vals?.otherUnitsAssistList.map((it) => ({ assistUserId: it })),
              id: drawer?.item?.id,
            };
            let res = await doFetch({
              url: '/repair/umOtherUnitsOrder/againOtherUnits',
              params,
            });
            if (res.code === '0000') {
              message.success('重新外协成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
        />
      </>
    );
  };

  // 外协派单
  const Wxpd = () => {
    const columns = [
      {
        title: '外协人员',
        dataIndex: 'otherUnitsAssistList',
        key: 'otherUnitsAssistList',
        valueType: 'select',
        options: { path: '/repair/umOtherUnitsOrder/selection', params: { id: drawer?.item.id } },
        formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
      },
    ];
    return (
      <>
        <InitForm
          fields={columns}
          onFinish={async (vals) => {
            let params = {
              otherUnitsAssistList: [{ assistUserId: vals?.otherUnitsAssistList }],
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umOtherUnitsOrder/dispatchById',
              params,
            });
            if (res.code === '0000') {
              message.success('派单成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
        />
      </>
    );
  };

  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 more = (text, row, _, action) => {
    const menu = (
      <Menu
        items={[
          {
            label:
              row?.status == 0 || row?.status == 1 ? (
                <a
                  onClick={async () => {
                    let params = {
                      id: row?.id,
                    };
                    let res = await doFetch({
                      url: '/repair/umOtherUnitsOrder/orderReceiving',
                      params,
                    });
                    if (res.code === '0000') {
                      message.success('接单成功！');
                      setdrawer((s) => ({
                        ...s,
                        open: false,
                      }));
                      actionRef.current.reload();
                    }
                  }}
                >
                  接单
                </a>
              ) : (
                <a
                  onClick={async () => {
                    setdrawer((s) => ({
                      ...s,
                      open: true,
                      type: 'wxpd',
                      item: row,
                      val: 'only',
                      title: '派单',
                    }));
                  }}
                >
                  派单
                </a>
              ),
            key: '0',
            // disabled: true,
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'comouts',
                    item: {
                      id: row.id,
                    },
                    val: 'only',
                    title: '完成外协',
                  }));
                }}
              >
                完成外协
              </a>
            ),
            key: '1',
          },
        ]}
      />
    );
    return (
      <Dropdown
        overlay={menu}
        trigger={['click']}
        arrow={true}
        getPopupContainer={() => containderef.current}
      >
        <Button size="small">更多</Button>
      </Dropdown>
    );
  };
  // 未完成按钮
  const unfinishBtn = (text, row, _, action) => {
    if (row?.status == 1 || row?.status == 2) {
      return (
        <PremButton
          pop={{
            title: '是否删除?',
            okText: '确认',
            cancelText: '取消',
            onConfirm: () => {
              run({ url: pathconfig?.delete || '/delete', params: { id: row?.id } });
            },
          }}
          btn={{
            size: 'small',
            type: 'danger',
          }}
        >
          删除
        </PremButton>
      );
    } else {
      return (
        <PremButton
          btn={{
            size: 'small',
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                item: {
                  ...row,
                  trackAssistList: row?.trackAssistList ? row?.trackAssistList : [],
                },
                title: '重新指派',
                type: 'Reassig',
                open: true,
              }));
            },
          }}
        >
          重新指派
        </PremButton>
      );
    }
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.columns;
    //console.log(defcolumn);
    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) => {
          return [more(text, row, _, action)];
        },
      });
    } else if (activeTabKey == '2') {
      return defcolumn.concat({
        title: '操作',
        valueType: 'option',
        width: 150,
        render: (text, row, _, action) => {
          return [unfinishBtn(text, row, _, action)];
        },
      });
    } else if (activeTabKey == '3') {
      return defcolumn;
    }
  }, [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/umOtherUnitsOrder/save'}
            setdrawer={setdrawer}
            actionRef={actionRef}
          />
        );
      case 'comouts':
        return <CompleteOuts />;
      case 'Reassig':
        return <Reassig />;
      case 'wxpd':
        return <Wxpd />;
      default:
        break;
    }
  };
  return (
    <div style={{ position: 'relative' }} ref={containderef}>
      <AutoTable
        pagetitle={<h3 className="page-title">外协工单</h3>}
        columns={columns}
        path={pathconfig?.list || '/ngic-auth/sysUser/query/page'}
        actionRef={actionRef}
        pageextra={pathconfig?.enableadd ? 'add' : null}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          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;
