/* 追踪工单
 * @Author: Li Hanlin
 * @Date: 2022-12-02 11:41:03
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-22 17:34:32
 */

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';
import Detail from '@/components/RepaireDetail/Detail';
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 Reassig = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '最新追踪人员',
              dataIndex: 'newRepairUserName',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              fieldProps: { disabled: true },
              key: 'newRepairUserName',
            },
            {
              title: '追踪人员',
              dataIndex: 'trackAssistList',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              fieldProps: {
                placeholder: '请选择',
                mode: 'multiple',
              },
              key: 'trackAssistList',
              valueType: 'select',
              options: {
                path: '/repair/umTrackOrder/selectionAgain',
                params: { id: drawer?.item.id },
              },
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              trackAssistList: vals?.trackAssistList.map((it) => ({ assistUserId: it })),
              id: drawer?.item?.id,
            };
            let res = await doFetch({
              url: '/repair/umTrackOrder/againTrack',
              params,
            });
            if (res.code === '0000') {
              message.success('重新指派成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          defaultFormValue={drawer?.item}
          {...drawer}
        />
      </>
    );
  };

  // 追踪
  const TrackForm = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '计划追踪日期',
              dataIndex: 'planTrackTime',
              formItemProps: { rules: [{ required: false, message: '此项为必填项' }] },
              key: 'nextTrackDate',
              fieldProps: {
                disabled: true,
              },
            },
            {
              title: '追踪结果',
              dataIndex: 'trackResult',
              valueType: 'radio',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              options: [
                {
                  value: '1',
                  label: '正常',
                },
                {
                  value: '2',
                  label: '异常',
                },
              ],
              colProps: { span: 24 },
              key: 'trackResult',
            },
            {
              title: '是否完成追踪',
              dataIndex: 'isFinishTrack',
              valueType: 'radio',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              colProps: { span: 24 },
              key: 'isFinishTrack',
              options: [
                {
                  value: '1',
                  label: '是',
                },
                {
                  value: '2',
                  label: '否',
                },
              ],
            },
            {
              title: '追踪周期',
              dataIndex: 'trackCycle',
              key: 'trackCycle',
              fieldProps: {
                disabled: true,
              },
            },
            {
              title: '追踪内容',
              dataIndex: 'trackContents',
              key: 'trackContents',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              valueType: 'textarea',
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              trackTraceinfo: { ...vals, planTrackTime: vals.nextTrackDate },
              id: drawer?.item?.id,
            };
            delete params.trackTraceinfo.nextTrackDate;
            //console.log(params);

            let res = await doFetch({
              url: '/repair/umTrackOrder/trackById',
              params,
            });
            if (res.code === '0000') {
              message.success('成功完成追踪！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          {...drawer}
          defaultFormValue={drawer?.item}
        />
      </>
    );
  };

  // 验证
  const CheckForm = () => {
    return (
      <>
        <InitForm
          fields={[
            {
              title: '追踪人员',
              dataIndex: 'trackerName',
              formItemProps: { rules: [{ required: false, message: '此项为必填项' }] },
              key: 'trackerName',
              fieldProps: {
                placeholder: '请选择',
                disabled: true,
              },
            },
            {
              title: '计划追踪日期',
              dataIndex: 'planTrackTime',
              key: 'planTrackTime',
              fieldProps: {
                placeholder: '请选择',
                disabled: true,
              },
            },
            {
              title: '实际追踪日期',
              dataIndex: 'actualTrackTime',
              fieldProps: {
                placeholder: '请选择',
                disabled: true,
              },
              key: 'actualTrackTime',
            },
            {
              title: '追踪结果',
              dataIndex: 'trackResults',
              fieldProps: {
                placeholder: '请选择',
                disabled: true,
              },
              key: 'trackResults',
            },
            {
              title: '追踪内容',
              dataIndex: 'trackContents',
              key: 'trackContents',
              fieldProps: {
                placeholder: '请选择',
                disabled: true,
              },
            },
            {
              title: '验证结果',
              dataIndex: 'reviewerResult',
              valueType: 'radio',
              formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
              options: [
                {
                  value: 1,
                  label: '通过',
                },
                {
                  value: 2,
                  label: '不通过',
                },
              ],
              key: 'reviewerResult',
            },
            {
              title: '备注',
              dataIndex: 'remark',
              valueType: 'textarea',
              formItemProps: { rules: [{ required: false, message: '此项为必填项' }] },
              key: 'remark',
            },
          ]}
          onFinish={async (vals) => {
            let params = {
              trackProcess: {
                reviewerResult: vals.reviewerResult,
                remark: vals.remark,
              },
              id: drawer?.item?.id,
            };
            let res = await doFetch({
              url: '/repair/umTrackOrder/verification',
              params,
            });
            if (res.code === '0000') {
              message.success('验证成功！');
              setdrawer((s) => ({
                ...s,
                open: false,
              }));
              actionRef.current.reload();
            }
          }}
          defaultFormValue={drawer?.item}
          {...drawer}
        />
      </>
    );
  };

  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/umTrackOrder/orderReceiving',
                      params,
                    });
                    if (res.code === '0000') {
                      message.success('接单成功！');
                      setdrawer((s) => ({
                        ...s,
                        open: false,
                      }));
                      actionRef.current.reload();
                    }
                  }}
                >
                  接单
                </a>
              ) : (
                <a
                  onClick={async () => {
                    let params = {
                      id: row?.id,
                    };
                    let res = await doFetch({
                      url: '/repair/umTrackOrder/dispatchById',
                      params,
                    });
                    if (res.code === '0000') {
                      message.success('派单成功！');
                      setdrawer((s) => ({
                        ...s,
                        open: false,
                      }));
                      actionRef.current.reload();
                    }
                  }}
                >
                  派单
                </a>
              ),
            key: '0',
            // disabled: true,
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    type: 'track',
                    item: { ...row, trackCycle: String(row?.trackCycle) },
                    // detailpath: '/repair/umTrackTraceinfo/queryByTrackOrderId',
                    // params: { trackOrderId: row?.id },
                    val: 'only',
                    title: '追踪信息',
                  }));
                }}
              >
                追踪
              </a>
            ),
            key: '1',
          },
          {
            label: (
              <a
                onClick={() => {
                  setdrawer((s) => ({
                    ...s,
                    open: true,
                    val: 'only',
                    title: '验证',
                    item: row,
                    detailpath: '/repair/umTrackTraceinfo/queryByTrackOrderId',
                    params: { trackOrderId: row?.id },
                    type: 'check',
                  }));
                }}
              >
                验证
              </a>
            ),
            key: '2',
          },
        ]}
      />
    );
    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 if (row?.status == 3) {
      return (
        <PremButton
          btn={{
            size: 'small',
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                item: {
                  ...row,
                  trackAssistList: row?.trackAssistList ? row?.trackAssistList : [],
                },
                type: 'Reassig',
                open: true,
                val: 'only',
              }));
              //console.log(drawer);
            },
          }}
        >
          重新指派
        </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 basecolumns = useMemo(() => {
    if (activeTabKey == 3) {
      return [
        {
          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',
        },
      ];
    } else {
      return [
        {
          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',
        },
      ];
    }
  }, [activeTabKey]);

  const selectType = (type) => {
    switch (type) {
      case 'add':
        return (
          <Addform url={'/repair/umTrackOrder/save'} setdrawer={setdrawer} actionRef={actionRef} />
        );
      case 'track':
        return <TrackForm />;
      case 'check':
        return <CheckForm />;
      case 'Reassig':
        return <Reassig />;
      case 'detail':
        return (
          <Detail
            title="追踪单号"
            titleno={drawer?.item?.taskOrderNo}
            detailpath="/repair/umTrackOperation/queryOperationList"
            params={{ trackOrderId: drawer?.item?.id }}
            baseRow={drawer?.item}
            basecolumns={basecolumns}
            type="zzgd"
          />
        );
      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;
