/* 维修工单
 * @Author: Li Hanlin
 * @Date: 2022-12-02 11:41:03
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-30 17:32:29
 */

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 { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
import { Dropdown, Menu, Button, message } from 'antd';
import InitForm from '@/components/InitForm';
import OrderHandle from '../platform/RepairOrderHandle';
import getcolumns from './columns';
import Detail from '@/components/RepaireDetail/Detail';

function Failure(props) {
  const 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 perData = useRequest(async () => {
    let res = await doFetch({
      url: '/auth/sysPermission/queryButton',
      params: { parentId: '400300' },
    });
    return res?.data?.dataList;
  });
  console.log(perData.data);
  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 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 More = (text, row, _, action) => {
    console.log(perData.data);
    
    const menu = (
      <Menu
        items={[
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'pd',
                    item: row,
                    val: 'only',
                    title: row?.status == 8 ? '派单' : '接单',
                  }));
                }}
              >
                {row?.status == 8 ? '派单' : '接单'}
              </a>
            ),
            key: '0',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'wcwx',
                    item: row,
                    val: 'only',
                    title: '完成维修',
                  }));
                }}
              >
                完成维修
              </a>
            ),
            key: '1',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'zzz',
                    item: row,
                    val: 'only',
                    title: '转追踪',
                  }));
                }}
              >
                转追踪
              </a>
            ),
            key: '2',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'zwx',
                    item: row,
                    val: 'only',
                    title: '转外协',
                  }));
                }}
              >
                转外协
              </a>
            ),
            key: '3',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'zd',
                    item: row,
                    val: 'only',
                    title: '转单',
                  }));
                }}
              >
                转单
              </a>
            ),
            key: '4',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'td',
                    item: row,
                    val: 'only',
                    title: '退单',
                  }));
                }}
              >
                退单
              </a>
            ),
            key: '5',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'xgyz',
                    item: row,
                    val: 'only',
                    title: '效果验证',
                  }));
                }}
              >
                效果验证
              </a>
            ),
            key: '6',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'zzsh',
                    item: row,
                    val: 'only',
                    title: '追踪审核',
                  }));
                }}
              >
                追踪审核
              </a>
            ),
            key: '7',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'wxsh',
                    item: row,
                    val: 'only',
                    title: '外协审核',
                  }));
                }}
              >
                外协审核
              </a>
            ),
            key: '8',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'tdsh',
                    item: row,
                    val: 'only',
                    title: '退单审核',
                  }));
                }}
              >
                退单审核
              </a>
            ),
            key: '9',
          },
        ]}
      />
    );
    return (
      <Dropdown
        overlay={menu}
        trigger={['click']}
        arrow={true}
        getPopupContainer={() => containderef.current}
      >
        <Button size="small">更多</Button>
      </Dropdown>
    );
  };

  // ++++++下拉菜单+++++++
  // 接单
  const Recevive = () => {
    return (
      <OrderHandle
        type="wxjd"
        id={drawer?.item.id}
        actionRef={actionRef}
        url="/repair/umRepairOrder/orderReceiving"
        setdrawer={setdrawer}
      />
    );
  };
  // 派单
  const Disp = () => {
    return (
      <OrderHandle
        type="wxpd"
        id={drawer?.item.id}
        actionRef={actionRef}
        url="/repair/umRepairOrder/dispatchById"
        setdrawer={setdrawer}
      />
    );
  };
  // 完成维修
  const Finishrepair = () => {
    const columns = [
      {
        title: '故障类型',
        dataIndex: 'faultSettingId',
        key: 'faultSettingId',
        valueType: 'select',
        options: {
          path: '/repair/umFaultSetting/selected/queryList',
          params: {
            equipmentId: drawer?.item.equipmentId,
          },
        },
      },
      {
        title: '故障名称',
        dataIndex: 'faultDetailId',
        key: 'faultDetailId',
        valueType: 'select',
        options: {
          path: '/repair/umFaultSettingDetail/selected/queryList',
          linkParams: {
            faultSettingId: '',
          },
        },
      },
      {
        title: '故障原因',
        dataIndex: 'faultCause',
        key: 'faultCause',
        valueType: 'textarea',
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必填项',
            },
          ],
        },
      },
      {
        title: '开始维修时间',
        dataIndex: 'repairTime',
        key: 'repairTime',
        fieldProps: {
          disabled: true,
        },
      },
      {
        title: '维修类型',
        dataIndex: 'repairType',
        key: 'repairType',
        valueType: 'select',
        options: {
          path: '/base/sysInitData/queryChildrenSelection',
          params: {
            parentId: 1,
          },
        },
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必填项',
            },
          ],
        },
      },
      {
        title: '是否停机维修',
        dataIndex: 'isShutdown',
        key: 'isShutdown',
        valueType: 'radio',
        options: [
          {
            value: 1,
            label: '是',
          },
          {
            value: 2,
            label: '否',
          },
        ],
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必填项',
            },
          ],
        },
      },
      {
        title: '维修内容',
        dataIndex: 'repairContent',
        key: 'repairContent',
        valueType: 'textarea',
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必填项',
            },
          ],
        },
      },
      {
        title: '协助维修人员',
        dataIndex: 'repairAssistList',
        key: 'repairAssistList',
        valueType: 'select',
        options: { path: '/repair/umRepairOrder/selection', params: { id: drawer?.item.id } },
        fieldProps: {
          placeholder: '请选择',
          showSearch: true,
          mode: 'multiple',
        },
      },
    ];
    return (
      <>
        <InitForm
          fields={columns}
          onFinish={async (vals) => {
            console.log(vals);
            let params = {
              repairComplete: {
                faultType: vals.faultSettingId,
                faultName: vals.faultDetailId,
                faultCause: vals.faultCause,
                repairType: vals.repairType,
                isShutdown: vals.isShutdown,
                repairContent: vals.repairContent,
              },

              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/completeRepair',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          defaultFormValue={drawer?.item}
          {...drawer}
        />
      </>
    );
  };
  // 转追踪
  const Toracking = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '申请追踪原因',
              dataIndex: 'reason',
              key: 'reason',
              valueType: 'textarea',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          onFinish={async (vals) => {
            console.log(vals);
            let params = {
              repairInfo: { ...vals },
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/transferTracking',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
        />
      </>
    );
  };
  // 转外协
  const Toout = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '申请外协原因',
              dataIndex: 'reason',
              key: 'reason',
              valueType: 'textarea',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              repairInfo: { ...vals },
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/transferOutsourcing',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
        />
      </>
    );
  };
  // 转单
  const Transfer = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '转单类型',
              dataIndex: 'reviewerType',
              key: 'reviewerType',
              valueType: 'select',
              options: {
                path: '/base/sysInitData/queryChildrenSelection',
                params: {
                  parentId: 2,
                },
              },
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '转单原因',
              dataIndex: 'reason',
              key: 'reason',
              valueType: 'textarea',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              repairInfo: { ...vals },
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/documentTransfer',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
        />
      </>
    );
  };
  // 退单
  const Singelback = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '退单原因',
              dataIndex: 'reason',
              key: 'reason',
              valueType: 'textarea',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              repairInfo: { ...vals },
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/chargeback',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
        />
      </>
    );
  };
  // 效果验证
  const EffectCheck = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '故障描述',
              dataIndex: 'faultDescription',
              key: 'faultDescription',
              valueType: 'textarea',
              fieldProps: {
                disabled: true,
              },
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              valueType: 'textarea',
              title: '故障原因',
              dataIndex: 'faultDescription',
              key: 'faultDescription',
              fieldProps: {
                disabled: true,
              },
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              valueType: 'textarea',
              title: '维修内容',
              dataIndex: 'faultDescription',
              key: 'faultDescription',
              fieldProps: {
                disabled: true,
              },
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '验证结果',
              dataIndex: 'resultFlag',
              key: 'resultFlag',
              valueType: 'radio',
              options: [
                { label: '通过', value: '1' },
                { label: '不通过', value: '2' },
              ],
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '备注',
              dataIndex: 'remaker',
              key: 'remaker',
              valueType: 'textarea',
              formItemProps: {
                rules: [
                  {
                    required: false,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              repairInfo: { ...vals },
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/completeRepairValidate',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
        />
      </>
    );
  };
  // 追踪审核
  const Rackaudit = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '申请追踪原因',
              dataIndex: 'reason',
              key: 'reson',
              fieldProps: {
                disabled: true,
              },
              formItemProps: {
                rules: [
                  {
                    required: false,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '审核结果',
              dataIndex: 'resultFlag',
              key: 'resultFlag',
              valueType: 'radio',
              options: [
                { label: '通过', value: '1' },
                { label: '不通过', value: '2' },
              ],
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '备注',
              dataIndex: 'remaker',
              key: 'remaker',
              valueType: 'textarea',
              formItemProps: {
                rules: [
                  {
                    required: false,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              repairProcess: { reviewerResult: vals.reviewerResult },
              resultFlag: vals.resultFlag,
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/transferTrackingAudit',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
        />
      </>
    );
  };
  // 外协审核
  const Outaudit = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '申请外协原因',
              dataIndex: 'reason',
              key: 'reson',
              fieldProps: {
                disabled: true,
              },
              formItemProps: {
                rules: [
                  {
                    required: false,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '审核结果',
              dataIndex: 'resultFlag',
              key: 'resultFlag',
              valueType: 'radio',
              options: [
                { label: '通过', value: '1' },
                { label: '不通过', value: '2' },
              ],
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '备注',
              dataIndex: 'remaker',
              key: 'remaker',
              valueType: 'textarea',
              formItemProps: {
                rules: [
                  {
                    required: false,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              repairProcess: { reviewerResult: vals.reviewerResult },
              resultFlag: vals.resultFlag,
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/transferAudit',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
        />
      </>
    );
  };
  // 退单审核
  const Backaudit = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '退单原因',
              dataIndex: 'reason',
              key: 'reson',
              fieldProps: {
                disabled: true,
              },
              formItemProps: {
                rules: [
                  {
                    required: false,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '审核结果',
              dataIndex: 'resultFlag',
              key: 'resultFlag',
              valueType: 'radio',
              options: [
                { label: '通过', value: '1' },
                { label: '不通过', value: '2' },
              ],
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '备注',
              dataIndex: 'remaker',
              key: 'remaker',
              valueType: 'textarea',
              formItemProps: {
                rules: [
                  {
                    required: false,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              repairProcess: { reviewerResult: vals.reviewerResult },
              resultFlag: vals.resultFlag,
              id: drawer?.item.id,
            };
            let res = await doFetch({
              url: '/repair/umRepairOrder/chargebackAudit',
              params,
            });
            if (res.code === '0000') {
              message.success('操作成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
        />
      </>
    );
  };

  const basecolumns = useMemo(() => {
    if (activeTabKey == 3) {
      return [
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '工单状态',
          dataIndex: 'statusName',
          key: 'statusName',
        },
        {
          title: '报修单号',
          dataIndex: 'repairNo',
          key: 'repairNo',
        },
        {
          title: '最新维修人员',
          dataIndex: 'newRepairUserName',
          key: 'newRepairUserName',
        },
        {
          title: '关单时间',
          dataIndex: 'repairCloseTime',
          key: 'repairCloseTime',
        },
      ];
    } else {
      return [
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '工单状态',
          dataIndex: 'statusName',
          key: 'statusName',
        },
        {
          title: '报修单号',
          dataIndex: 'repairNo',
          key: 'repairNo',
        },
        {
          title: '最新维修人员',
          dataIndex: 'newRepairUserName',
          key: 'newRepairUserName',
        },
      ];
    }
  }, [activeTabKey]);

  const selectType = {
    jd: <Recevive />,
    pd: <Disp />,
    wcwx: <Finishrepair />,
    zzz: <Toracking />,
    zwx: <Toout />,
    zd: <Transfer />,
    td: <Singelback />,
    xgyz: <EffectCheck />,
    zzsh: <Rackaudit />,
    wxsh: <Outaudit />,
    tdsh: <Backaudit />,
    detail: (
      <Detail
        title="维修单号"
        titleno={drawer?.item?.repairNo}
        detailpath="/repair/umRepairOperation/queryOperationList"
        params={{ repairOrderId: drawer?.item?.id }}
        baseRow={drawer?.item}
        basecolumns={basecolumns}
        type="wxgd"
      />
    ),
  };

  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) => [More(text, row, _, action)],
      });
    } else {
      return defcolumn;
    }
  }, [activeTabKey]);

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

  const containderef = useRef();
  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}
        resizeable={false}
        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;
