/* 接单平台
 * @Author: Li Hanlin
 * @Date: 2022-12-05 10:13:42
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-30 13:18:22
 */

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 OrderHandle from './RepairOrderHandle';
import { message } from 'antd';
import Detail from '@/components/RepaireDetail/Detail';
function Platform(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 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 receiveBtn = (text, row, _, action, activeTab) => {
    if (row?.status == 0 || row?.status == 1) {
      if (activeTab == '2') {
        // 追踪
        return (
          <PremButton
            btn={{
              size: 'small',
              type: 'primary',
              onClick: async () => {
                debugger;
                // setdrawer((s) => ({
                //   ...s,
                //   type: null,
                // }));
                //console.log('zzjd');
                let params = {
                  id: row?.id,
                };
                let res = await doFetch({
                  url: '/repair/umTrackOrder/orderReceiving',
                  params,
                });
                if (res.code === '0000') {
                  message.success('操作成功！');
                  setdrawer((s) => ({
                    ...s,
                    open: false,
                  }));
                  actionRef.current.reload();
                }
              },
            }}
          >
            接单
          </PremButton>
        );
      } else if (activeTab == '3') {
        return (
          <PremButton
            btn={{
              size: 'small',
              type: 'primary',
              onClick: async () => {
                let params = {
                  ...vals,
                  id,
                };
                let res = await doFetch({
                  url: '/repair/umOtherUnitsOrder/orderReceiving',
                  params,
                });
                if (res.code === '0000') {
                  message.success('操作成功！');
                  setdrawer((s) => ({
                    ...s,
                    open: false,
                  }));
                  actionRef.current.reload();
                }
              },
            }}
          >
            接单
          </PremButton>
        );
      } else if (activeTab == '1') {
        // 维修
        return (
          <PremButton
            btn={{
              size: 'small',
              type: 'primary',
              onClick: () => {
                setdrawer((s) => ({
                  ...s,
                  open: true,
                  item: row,
                  title: '接单',
                  val: 'only',
                  type: 'wxjd',
                }));
              },
            }}
          >
            接单
          </PremButton>
        );
      }
    } else {
      if (activeTab == '2') {
        return (
          <PremButton
            btn={{
              size: 'small',
              type: 'primary',
              onClick: () => {
                setdrawer((s) => ({
                  ...s,
                  open: true,
                  item: row,
                  title: '派单',
                  type: 'zzpd',
                  val: 'only',
                }));
              },
            }}
          >
            派单
          </PremButton>
        );
      } else if (activeTab == '1') {
        // 维修
        return (
          <PremButton
            btn={{
              size: 'small',
              type: 'primary',
              onClick: () => {
                setdrawer((s) => ({
                  ...s,
                  open: true,
                  item: row,
                  title: '派单',
                  type: 'wxpd',
                  val: 'only',
                }));
              },
            }}
          >
            派单
          </PremButton>
        );
      } else if (activeTab == '3') {
        return (
          <PremButton
            btn={{
              size: 'small',
              type: 'primary',
              onClick: () => {
                setdrawer((s) => ({
                  ...s,
                  open: true,
                  item: row,
                  title: '派单',
                  type: 'wpd',
                  val: 'only',
                }));
              },
            }}
          >
            派单
          </PremButton>
        );
      }
    }
  };

  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 ?? {};
    let actions = {
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => receiveBtn(text, row, _, action, activeTabKey),
    };
    return defcolumn.concat(actions);
  }, [activeTabKey]);

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

  function selectType(type) {
    switch (type) {
      case 'wxjd':
        return (
          <OrderHandle
            type="wxjd"
            id={drawer?.item.id}
            url={'/repair/umRepairOrder/orderReceiving'}
            actionRef={actionRef}
            setdrawer={setdrawer}
          />
        );
      case 'wxpd':
        return (
          <OrderHandle
            type="wxpd"
            actionRef={actionRef}
            setdrawer={setdrawer}
            id={drawer?.item.id}
            url={'/repair/umRepairOrder/dispatchById'}
          />
        );
      case 'zzpd':
        return (
          <OrderHandle
            type="zzpd"
            actionRef={actionRef}
            setdrawer={setdrawer}
            id={drawer?.item.id}
            url={'/repair/umTrackOrder/dispatchById'}
          />
        );
      case 'wpd':
        return (
          <OrderHandle
            type="wpd"
            setdrawer={setdrawer}
            actionRef={actionRef}
            id={drawer?.item.id}
            url={'/repair/umOtherUnitsOrder/dispatchById'}
          />
        );
      case 'detail_wxgd':
        return (
          <Detail
            title="维修单号"
            titleno={drawer?.item?.repairNo}
            detailpath="/repair/umRepairOperation/queryOperationList"
            params={{ repairOrderId: drawer?.item?.id }}
            baseRow={drawer?.item}
            basecolumns={[
              {
                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',
              },
            ]}
            type="wxgd"
          />
        );
      case 'detail_wgd':
        return (
          <Detail
            title="外协单号"
            titleno={drawer?.item.otherUnitsOrderNo}
            detailpath="/repair/umOtherUnitsOperation/queryOperationList"
            params={{ otherUnitsOrderId: drawer?.item.id }}
            baseRow={drawer?.item}
            basecolumns={[
              {
                title: '创建人',
                dataIndex: 'createUserName',
                key: 'createUserName',
              },
              {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
              },
              {
                title: '工单状态',
                dataIndex: 'statusName',
                key: 'statusName',
              },
              {
                title: '来源工单',
                dataIndex: 'dataSourcesNo',
                key: 'dataSourcesNo',
              },
              {
                title: '来源类型',
                dataIndex: 'dataSourcesName',
                key: 'dataSourcesName',
              },
              {
                title: '最新外协人员',
                dataIndex: 'newRepairUserName',
                key: 'newRepairUserName',
              },
              {
                title: '关单时间',
                dataIndex: 'repairCloseTime',
                key: 'repairCloseTime',
              },
            ]}
            type="wgd"
          />
        );
      case 'detail_zzgd':
        return (
          <Detail
            title="追踪单号"
            titleno={drawer?.item?.taskOrderNo}
            detailpath="/repair/umTrackOperation/queryOperationList"
            params={{ trackOrderId: drawer?.item?.id }}
            baseRow={drawer?.item}
            basecolumns={[
              {
                title: '创建人',
                dataIndex: 'createUserName',
                key: 'createUserName',
              },
              {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
              },
              {
                title: '工单状态',
                dataIndex: 'statusName',
                key: 'statusName',
              },
              {
                title: '来源工单',
                dataIndex: 'dataSourcesNo',
                key: 'dataSourcesNo',
              },
              {
                title: '来源类型',
                dataIndex: 'dataSourcesName',
                key: 'dataSourcesName',
              },
              {
                title: '最新追踪人员',
                dataIndex: 'newRepairUserName',
                key: 'newRepairUserName',
              },
              {
                title: '下次追踪日期',
                dataIndex: 'nextTrackDate',
                key: 'nextTrackDate',
              },
              {
                title: '关单时间',
                dataIndex: 'repairCloseTime',
                key: 'repairCloseTime',
              },
            ]}
            type="zzgd"
          />
        );
      default:
        break;
    }
  }
  return (
    <div style={{ position: 'relative' }}>
      <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,
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: null,
                title: '新增',
                val: 'add',
              }));
            },
          },
        }}
        tabList={getcolumns()}
        activeTabKey={activeTabKey}
        onTabChange={(key) => {
          setactiveTabKey(key);
        }}
      />

      <DrawerPro
        fields={columns}
        detailpath={pathconfig?.detail || null}
        detailData={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 Platform;
