/* 保养工单
 * @Author: Li Hanlin
 * @Date: 2023-01-19 09:53:59
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2023-02-27 17:21:42
 */

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 AutoTables from '@/components/AutoTable/mtable';
import { Radio, InputNumber, Input, Divider, message } from 'antd';
import InitForm from '@/components/InitForm';
import getDetailColumns from './detailColumns';
import { useModel } from '@umijs/max';
import DetailNode from '@/components/DetailNode';

function WorkOrder(props) {
  const { initialState, setInitialState } = useModel('@@initialState');

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

  const { run, loading, runAsync } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, params) => {
      if (res?.code == '0000') {
        message.success('操作成功!');
        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 detailaddonColumns = useMemo(() => {
    if (activeTabKey == 1) {
      if (drawer?.type == 'yz') {
        const columnsc = [
          {
            title: '保养项目',
            dataIndex: 'maintainItemName',
            key: 'maintainItemName',
            hideInForm: true,
          },
          {
            title: '部位',
            dataIndex: 'maintainPosition',
            key: 'maintainPosition',
            hideInForm: true,
          },
          {
            title: '保养方法',
            dataIndex: 'maintainMethod',
            key: 'maintainMethod',
            hideInForm: true,
          },
          {
            title: '结果',
            dataIndex: 'qualitativeJudgeResult',
            key: 'qualitativeJudgeResult',
            hideInForm: true,
            render: (_, row) => {
              if (row?.judgeType == 1) {
                return row?.judgeResultName;
              } else {
                return row?.qualitativeJudgeResult;
              }
            },
          },
          {
            title: '下限值',
            dataIndex: 'lowerLimit',
            key: 'lowerLimit',
            hideInForm: true,
          },
          {
            title: '上限值',
            dataIndex: 'upperLimit',
            key: 'upperLimit',
            hideInForm: true,
          },
          {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            hideInForm: true,
          },
        ];
        return [
          {
            title: '工单信息',
            valueType: 'split',
          },
          {
            title: '保养单号',
            dataIndex: 'taskNo',
            key: 'taskNo',
          },
          {
            title: '设备编号',
            dataIndex: 'equipmentNo',
            key: 'equipmentNo',
          },
          {
            title: '设备名称',
            dataIndex: 'equipmentName',
            key: 'equipmentName',
          },
          {
            title: '保养类型',
            dataIndex: 'maintainTypeName',
            key: 'maintainTypeName',
          },

          {
            title: '保养频次',
            dataIndex: 'maintainFrequencyName',
            key: 'maintainFrequency',
          },
          {
            title: '保养截止日期',
            dataIndex: 'planMaintainDate',
            key: 'planMaintainDate',
          },
          {
            title: '接单时间',
            dataIndex: 'maintainStartTime',
            key: 'maintainStartTime',
          },
          {
            title: '完成保养时间',
            dataIndex: 'maintainEndTime',
            key: 'maintainEndTime',
          },
          {
            title: '保养项目',
            valueType: 'split',
          },
          {
            dataIndex: 'itemList',
            key: 'itemList',
            valueType: 'formList',
            columns,
            span: 3,
            render: (text, row, _, action) => {
              return (
                <AutoTables
                  columns={columnsc?.map((it) => ({
                    ...it,
                    hideInSearch: true,
                  }))}
                  dataSource={drawer?.item?.maintainTaskItemList}
                />
              );
            },
          },
        ];
      } else if (drawer?.type == 'wcby') {
        const columnsc = [
          {
            title: '保养项目',
            dataIndex: 'maintainItemName',
            key: 'maintainItemName',
            hideInForm: true,
          },
          {
            title: '部位',
            dataIndex: 'maintainPosition',
            key: 'maintainPosition',
            hideInForm: true,
          },
          {
            title: '保养方法',
            dataIndex: 'maintainMethod',
            key: 'maintainMethod',
            hideInForm: true,
          },
          {
            title: '结果',
            dataIndex: 'result',
            key: 'result',
            hideInForm: true,
            render: (text, row, _, action) => {
              return row.judgeType == 1 ? (
                <Radio.Group
                  onChange={(e) => {
                    row.result = e.target.value;
                  }}
                >
                  <Radio value={1}>正常</Radio>
                  <Radio value={2}>异常</Radio>
                </Radio.Group>
              ) : (
                <InputNumber
                  onChange={(value) => {
                    row.result = value;
                  }}
                />
              );
            },
          },
          {
            title: '下限值',
            dataIndex: 'lowerLimit',
            key: 'lowerLimit',
            hideInForm: true,
          },
          {
            title: '上限值',
            dataIndex: 'upperLimit',
            key: 'upperLimit',
            hideInForm: true,
          },
          {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            hideInForm: true,
            render: (text, row, _, action) => {
              return (
                <Input
                  onChange={(e) => {
                    row.remark = e.target.value;
                  }}
                />
              );
            },
          },
        ];
        return [
          {
            title: '工单信息',
            valueType: 'split',
          },
          {
            title: '保养单号',
            dataIndex: 'taskNo',
            key: 'taskNo',
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
          },
          {
            title: '工单状态',
            dataIndex: 'taskStatusName',
            key: 'taskStatusName',
          },
          {
            title: '保养计划单号',
            dataIndex: 'maintainNo',
            key: 'maintainNo',
          },
          {
            title: '设备编号',
            dataIndex: 'equipmentNo',
            key: 'equipmentNo',
          },
          {
            title: '设备名称',
            dataIndex: 'equipmentName',
            key: 'equipmentName',
          },
          {
            title: '设备型号',
            dataIndex: 'equipmentModelName',
            key: 'equipmentModelName',
          },
          {
            title: '保养类型',
            dataIndex: 'maintainTypeName',
            key: 'maintainTypeName',
          },
          {
            title: '保养频次',
            dataIndex: 'maintainFrequencyName',
            key: 'maintainFrequency',
          },
          {
            title: '保养截止日期',
            dataIndex: 'planMaintainDate',
            key: 'planMaintainDate',
          },
          {
            title: '接单时间',
            dataIndex: 'maintainStartTime',
            key: 'maintainStartTime',
            span: 2,
          },
          {
            title: '保养项目',
            valueType: 'split',
          },
          {
            dataIndex: 'itemList',
            key: 'itemList',
            valueType: 'formList',
            columns,
            span: 3,
            render: (text, row, _, action) => {
              return (
                <AutoTables
                  columns={columnsc?.map((it) => ({
                    ...it,
                    hideInSearch: true,
                  }))}
                  dataSource={drawer?.item?.maintainTaskItemList}
                />
              );
            },
          },
        ];
      }
    }
  }, [drawer?.item, activeTabKey]);

  const order = (text, row, _, action) => {
    return (
      <PremButton
        access="umMaintainTask_orderReceiving"
        pop={{
          title: '是否接单?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            await runAsync({
              url: '/maintain/umMaintainTask/orderReceiving',
              params: { id: row?.id },
            });
          },
        }}
        btn={{
          size: 'small',
        }}
      >
        接单
      </PremButton>
    );
  };
  const close = (text, row, _, action) => {
    return (
      <PremButton
        access="umMaintainTask_customsDeclaration"
        pop={{
          title: '是否关单?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            await runAsync({
              url: '/maintain/umMaintainTask/customsDeclaration',
              params: { id: row?.id },
            });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        关单
      </PremButton>
    );
  };
  const finish = (text, row, _, action) => {
    return (
      <PremButton
        access="umMaintainTask_finishMaintainTask"
        btn={{
          size: 'small',
          onClick: () => {
            doFetch({
              url: '/maintain/umMaintainTask/queryById',
              params: { id: row.id },
            }).then((res) => {
              if (res.code == '0000') {
                setdrawer((s) => ({
                  ...s,
                  open: true,
                  item: {
                    ...res.data?.data,
                    id: row.id,
                  },
                  title: '完成保养',
                  val: 'detailaddon',
                  type: 'wcby',
                }));
              }
            });
          },
        }}
      >
        完成保养
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        access="umMaintainTask_deleteById"
        pop={{
          title: '是否删除?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: () => {
            run({ url: pathconfig?.delete || '/delete', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  const verify = (text, row, _, action) => {
    return (
      <PremButton
        access="umMaintainTask_verification"
        btn={{
          size: 'small',
          onClick: () => {
            doFetch({
              url: '/maintain/umMaintainTask/queryById',
              params: { id: row.id },
            }).then((res) => {
              if (res.code == '0000') {
                setdrawer((s) => ({
                  ...s,
                  open: true,
                  item: {
                    ...res.data?.data,
                    id: row.id,
                  },
                  title: '验证',
                  val: 'detailaddon',
                  type: 'yz',
                }));
              }
            });
          },
        }}
      >
        验证
      </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 ?? {};
    return activeTabKey == 1
      ? defcolumn.concat({
          title: '操作',
          valueType: 'option',
          width: 150,
          render: (text, row, _, action) => {
            if (row?.taskStatus == 1) {
              return [order(text, row, _, action), close(text, row, _, action)];
            } else if (row?.taskStatus == 2) {
              return [finish(text, row, _, action)];
            } else if (row?.taskStatus == 5) {
              return [verify(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 seletType = {
    wcby: (
      <div>
        <InitForm
          fields={[
            {
              title: (
                <span style={{ fontSize: 14, fontWeight: 600, color: '#262626' }}>
                  非寿命件消耗
                </span>
              ),
              valueType: 'split',
            },
            {
              dataIndex: 'lineStockUseList',
              key: 'lineStockUseList',
              valueType: 'formSelectList',
              colProps: {
                span: 24,
              },
              span: 3,
              columns: [
                {
                  title: '线边库',
                  dataIndex: 'stockName',
                  key: 'stockName',
                  editable: false,
                },
                {
                  title: '备件料号',
                  dataIndex: 'sparePartNo',
                  key: 'sparePartNo',
                  span: 3,
                  editable: false,
                },
                {
                  title: '备件名称',
                  dataIndex: 'sparePartName',
                  key: 'sparePartName',
                  span: 3,
                  editable: false,
                },
                {
                  title: '供应商编号',
                  dataIndex: 'supplierNo',
                  key: 'supplierNo',
                  span: 3,
                  editable: false,
                },
                {
                  title: '供应商名称',
                  dataIndex: 'supplierName',
                  key: 'supplierName',
                  span: 3,
                  editable: false,
                },
                {
                  title: '可用数量',
                  dataIndex: 'usedStock',
                  key: 'usedStock',
                  search: false,
                  span: 3,
                  editable: false,
                },
                {
                  title: (
                    <div>
                      消耗数量 <span style={{ color: 'red' }}>* </span>
                    </div>
                  ),
                  search: false,
                  dataIndex: 'operateNum',
                  valueType: 'digit',
                  fieldProps: {
                    precision: 3,
                  },
                  key: 'operateNum',
                },
              ],
              hideInSearch: true,
              hideInTable: true,
              path: '/sparepart/lineStock/queryConsumeStock',
              rowName: 'lineStockUseList',
              rowSelection: {
                type: 'checkbox',
                getCheckboxProps: (record) => ({
                  disabled: record.isAsh == '1',
                }),
              },
            },
            {
              title: (
                <span style={{ fontSize: 14, fontWeight: 600, color: '#262626' }}>寿命件更换</span>
              ),
              valueType: 'split',
            },
            {
              dataIndex: 'lifePieceStockUseList',
              key: 'lifePieceStockUseList',
              valueType: 'Expandable',
              colProps: {
                span: 24,
              },
              columns: [
                {
                  title: '备件料号',
                  dataIndex: 'sparePartNo',
                  key: 'sparePartNo',
                },
                {
                  title: '备件名称',
                  dataIndex: 'sparePartName',
                  key: 'sparePartName',
                },
                {
                  title: '供应商编号',
                  dataIndex: 'supplierNo',
                  key: 'supplierNo',
                  search: false,
                },
                {
                  title: '供应商名称',
                  dataIndex: 'supplierName',
                  search: false,
                  key: 'supplierName',
                },
                {
                  title: '安装部位',
                  dataIndex: 'installPosition',
                  key: 'installPosition',
                },
                {
                  title: '安装数量',
                  dataIndex: 'installNum',
                  search: false,
                  key: 'installNum',
                },
                {
                  title: '下次更换日期',
                  dataIndex: 'nextReplaceDate',
                  key: 'nextReplaceDateList',
                  valueType: 'dateRange',
                },
              ],
              path: '/sparepart/lifePieceAccount/queryPageByEquipment',
              extraparams: { equipmentId: drawer?.item?.equipmentId },
              expandablePath: '/sparepart/lineStock/queryReplaceStockAll',
            },
          ]}
          onFinish={(vals) => {
            console.log(vals);
            let maintainTaskItemList = drawer?.item?.maintainTaskItemList?.map((it) => {
              if (it.judgeType == 1) {
                return {
                  id: it.id,
                  remark: it.remark,
                  judgeResultType: it.result,
                };
              } else {
                return {
                  id: it.id,
                  remark: it.remark,
                  qualitativeJudgeResult: it.result,
                };
              }
            });
            let lineStockUseList =
              vals?.lineStockUseList?.map((it) => ({
                lineStockId: it?.id,
                operateNum: it?.operateNum,
              })) ?? [];
            let lifePieceStockUseList = vals?.lifePieceStockUseList ?? [];
            run({
              url: '/maintain/umMaintainTask/finishMaintainTask',
              params: {
                id: drawer?.item?.id,
                maintainTaskItemList,
                lineStockUseList,
                lifePieceStockUseList,
              },
            });
          }}
        />
      </div>
    ),
    yz: (
      <div>
        <Divider />
        <InitForm
          fields={[
            {
              title: '验证结果',
              valueType: 'select',
              dataIndex: 'approveStatus',
              key: 'approveStatus',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
              options: [
                {
                  value: '1',
                  label: '通过',
                },
                {
                  value: '2',
                  label: '不通过',
                },
              ],
            },
            {
              title: '备注',
              valueType: 'textarea',
              dataIndex: 'approveContent',
              key: 'approveContent',
            },
          ]}
          onFinish={(vals) => {
            run({
              url: '/maintain/umMaintainTask/verification',
              params: { ...vals, id: drawer?.item?.id },
            });
          }}
        />
      </div>
    ),
  };

  const DetailLine = () => {
    return (
      <>
        <DetailNode
          path="/maintain/umMaintainTaskOperation/queryDetailList"
          params={
            activeTabKey == 3
              ? { maintainTaskId: drawer?.item?.equipmentMaintainTaskId }
              : { maintainTaskId: drawer?.item?.id }
          }
          titleColumns={
            activeTabKey == 3
              ? [
                  {
                    title: '保养单号',
                    dataIndex: 'taskNo',
                    key: 'taskNo',
                  },
                  {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                  },
                  {
                    title: '工单状态',
                    dataIndex: 'taskStatusName',
                    key: 'taskStatusName',
                  },
                  {
                    title: '保养计划单号',
                    dataIndex: 'maintainNo',
                    key: 'maintainNo',
                  },
                  {
                    title: '关单时间',
                    dataIndex: 'customsTime',
                    key: 'customsTime',
                  },
                ]
              : [
                  {
                    title: '保养单号',
                    dataIndex: 'taskNo',
                    key: 'taskNo',
                  },
                  {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                  },
                  {
                    title: '工单状态',
                    dataIndex: 'taskStatusName',
                    key: 'taskStatusName',
                  },
                  {
                    title: '保养计划单号',
                    dataIndex: 'maintainNo',
                    key: 'maintainNo',
                  },
                ]
          }
          detailKey="maintainTaskItemList"
          columns={getDetailColumns}
        />
      </>
    );
  };

  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">保养工单</h3>}
        columns={columns}
        path={pathconfig?.list || '/ngic-auth/sysUser/query/page'}
        extraparams={activeTabKey == 1 ? { mainUserId: initialState?.currentUser?.id } : null}
        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={detailaddonColumns}
        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 } });
          }
        }}
      >
        {drawer?.val == 'only' ? (
          <DetailLine />
        ) : drawer?.val == 'detailaddon' ? (
          seletType[drawer?.type]
        ) : null}
      </DrawerPro>
    </div>
  );
}

export default WorkOrder;