import React, { useEffect, useReducer, useRef } from "react";
import {
  Button,
  Drawer,
  Steps,
  Form,
  Popconfirm,
  Switch,
  Tabs,
  Card,
  Row,
  Col,
  Tooltip,
} from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import InitForm from "@/components/InitForm";
import { useRequest } from "umi";
import { addFields } from "./fields";
import { doFetch } from "@/utils/doFetch";
import moment from "moment";
import { dispatchorderDetail } from "@/utils/detailTotalCard";
import Coltext from "@/components/Coltext";
import Details from "@/components/Details";
import styles from "./index.less";
import Scheduling from "./Scheduling";
import Setsort from "./Setsort";
const { Step } = Steps,
  { TabPane } = Tabs,
  otherBasic = {
    processLineCode: "工艺路线编号",
    processLineName: "工艺路线名称",
    factoryName: "所属工厂",
    shopName: "所属车间",
  },
  tabList = [
    {
      key: "1",
      tab: "未完成",
    },
    {
      key: "2",
      tab: "已完成",
    },
  ];
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  currentStep: 0,
  orderId: "",
  fieldsValue: {},
  btnLoading: false,
  tabeTep: [],
  editType: "",
  fieldsc: {},
  visible: false,
  expandedRowKeys: [],
  tabKey: "",
  detail: {
    dataSource: {},
    totalCard: [],
  },
  detailsVisible: false,
  detailStepData: {},
  activeTabKey: "1",
  schedulingVisible: false,
};
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case "add":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "新增派工单",
          val: type,
        },
        fields: { ...action.fields },
      };
      break;
    case "addBom":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: "新增物料BOM",
          val: type,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      break;
    case "addProcess":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: action.title,
          val: type,
          isTopRightAdd: action.isTopRightAdd,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      break;
    case "edit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "修改派工单",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
        editType: action.editType,
      };
      break;
    case "editBom":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: "编辑物料BOM",
          val: type,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      break;
    case "editIssue":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: "修改派工单",
          val: type,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      break;
    case "setCurrent":
      newState = {
        ...state,
        currentStep: action.currentStep,
      };
      break;
    case "changeOrderId":
      newState = {
        ...state,
        orderId: action.orderId,
      };
      break;
    case "changeValues":
      newState = {
        ...state,
        fieldsValue: { ...action.fieldsValue },
      };
      break;
    case "changeactiveTabKey":
      newState = {
        ...state,
        activeTabKey: action.activeTabKey,
      };
      break;
    case "changeLoading":
      newState = {
        ...state,
        btnLoading: action.btnLoading,
      };
      break;
    case "changeTableTep":
      newState = {
        ...state,
        tabeTep: action.tabeTep,
      };
      break;
    case "changeFields":
      newState = {
        ...state,
        fields: { ...action.fields },
      };
      break;
    case "changeEditType":
      newState = {
        ...state,
        editType: action.editType,
      };
      break;
    case "closeBom":
      newState = {
        ...state,
        fieldsc: {},
        visible: false,
      };
      break;
    case "changeExpand":
      newState = {
        ...state,
        expandedRowKeys: action.expandedRowKeys,
      };
      break;
    case "changeTabKey":
      newState = {
        ...state,
        tabKey: action.tabKey,
      };
      break;
    case "see":
      newState = {
        ...state,
        detail: {
          dataSource: action.dataSource,
          totalCard: action.totalCard,
        },
        detailsVisible: true,
        detailStepData: action.detailStepData,
      };
      break;
    case "scheduling":
      newState = {
        ...state,
        schedulingVisible: true,
        iftype: {
          title: "计划排产",
          val: type,
        },
      };
      break;
    case "sort":
      newState = {
        ...state,
        schedulingVisible: true,
        iftype: {
          title: "产线排序",
          val: type,
        },
      };
      break;
    case "close":
      newState = {
        ...state,
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        currentStep: 0,
        orderId: "",
        btnLoading: false,
        tabeTep: [],
        fieldsValue: {},
        editType: "",
        fieldsc: {},
        visible: false,
        expandedRowKeys: [],
        tabKey: "",
        detailsVisible: false,
        detail: {
          dataSource: {},
          totalCard: [],
        },
        detailStepData: {},
        schedulingVisible: false,
      };
      break;
  }

  return newState;
}
const Dispatchorder = (props) => {
  let actionRef = useRef(),
    ChildRef = null,
    [formRef] = Form.useForm(),
    actionRefs = useRef(),
    actionRefc = useRef();
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  function reloads() {
    actionRefc?.current?.reload();
    actionRefs?.current?.reload();
    dispatch({ type: "closeBom" });
  }
  function reset() {
    reload();
    dispatch({ type: "close" });
  }
  let extrarender = [
      <Button
        disabled={!getPrem("sysDepartment_save", "ifs")}
        type="primary"
        onClick={() => {
          for (let i in addFields) {
            addFields[i].value = null;
            addFields[i].disabled = false;
          }
          dispatch({ type: "add", fields: addFields });
        }}
      >
        新增
      </Button>,
      <Button
        disabled={!getPrem("sysDepartment_save", "ifs")}
        style={{ margin: "0 15px" }}
        onClick={() => {
          dispatch({ type: "scheduling" });
        }}
      >
        排产
      </Button>,
      <Button
        disabled={!getPrem("sysDepartment_save", "ifs")}
        onClick={() => {
          dispatch({ type: "sort" });
        }}
      >
        排序
      </Button>,
    ],
    extrarenders = [
      <Button
        disabled={!getPrem("sysDepartment_save", "ifs")}
        type="primary"
        onClick={() => {
          if (currentStep == 1) {
            addBomFn({ materieId: fieldsValue.materieId }, null);
          } else if (currentStep == 2) {
            addProcessFn(null, true, "新增步骤和工序");
          }
        }}
      >
        新增
      </Button>,
    ];
  const { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          reloads();
        }
      },
    }),
    [state, dispatch] = useReducer(reducer, initState),
    {
      vs,
      fields,
      iftype,
      curitem,
      currentStep,
      orderId,
      fieldsValue,
      btnLoading,
      tabeTep,
      editType,
      visible,
      fieldsc,
      expandedRowKeys,
      tabKey,
      detail,
      detailsVisible,
      detailStepData,
      activeTabKey,
      schedulingVisible,
    } = state,
    columns = [
      {
        title: "派工单编号",
        dataIndex: "jobOrderNo",
        key: "jobOrderNo",
        render: (_, row) => {
          return (
            <Tooltip title={row.jobOrderNo}>
              <a
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-production/umJobOrder/queryDetailById",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {};
                      let bottom = [
                          {
                            cardTitle: "物料BOM信息",
                            itemData: [
                              {
                                key: "umJobOrderMaterieBomList",
                                rowKey: "key",
                                type: "table",
                                columns: [
                                  {
                                    title: "物料编号",
                                    dataIndex: "title",
                                    key: "title",
                                    search: false,
                                  },
                                  {
                                    title: "物料名称",
                                    dataIndex: "materieName",
                                    key: "materieName",
                                    search: false,
                                  },
                                  {
                                    title: "生产单位",
                                    dataIndex: "productionUnitName",
                                    key: "productionUnitName",
                                    search: false,
                                  },
                                  {
                                    title: "物料类别",
                                    dataIndex: "materieTypeName",
                                    key: "materieTypeName",
                                    search: false,
                                  },
                                  {
                                    title: "台份量",
                                    dataIndex: "numberUnits",
                                    key: "numberUnits",
                                    search: false,
                                  },
                                  {
                                    title: "预投量",
                                    dataIndex: "planQuantity",
                                    key: "planQuantity",
                                    search: false,
                                  },
                                  {
                                    title: "产出工序",
                                    dataIndex: "workingProduceName",
                                    key: "workingProduceName",
                                    search: false,
                                  },
                                  {
                                    title: "投料工序",
                                    dataIndex: "workingFeedingName",
                                    key: "workingFeedingName",
                                    search: false,
                                  },
                                ],
                                col: { span: 24 },
                                expandable: {
                                  defaultExpandedRowKeys:
                                    dataSource.umJobOrderMaterieBomList
                                      ?.length > 0
                                      ? [
                                          dataSource.umJobOrderMaterieBomList[0]
                                            ?.key,
                                        ]
                                      : [],
                                },
                              },
                            ],
                          },
                        ],
                        totalCard = [...dispatchorderDetail, ...bottom];
                      dispatch({
                        type: "see",
                        dataSource,
                        detailStepData: dataSource?.umJobOrderProcessLine ?? {},
                        totalCard,
                      });
                    }
                  });
                }}
              >
                {row.jobOrderNo}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "物料编号",
        dataIndex: "materieCode",
        key: "materieCode",
      },
      {
        title: "物料名称",
        dataIndex: "materieName",
        key: "materieName",
      },
      {
        title: "生产单位",
        dataIndex: "productionUnitName",
        key: "productionUnitName",
        search: false,
      },
      {
        title: "车间",
        dataIndex: "shopName",
        key: "shopName",
      },
      {
        title: "产线",
        dataIndex: "productionLineName",
        key: "productionLineName",
      },
      {
        title: "班次",
        dataIndex: "shiftName",
        key: "shiftName",
      },
      {
        title: "班组",
        dataIndex: "groupName",
        key: "groupName",
        search: false,
      },
      {
        title: "排产数量",
        dataIndex: "scheduledProductionNum",
        key: "scheduledProductionNum",
        search: false,
      },
      {
        title: "生产日期",
        dataIndex: "productionDate",
        key: "productionDate",
        search: false,
      },
      {
        title: "生产订单编号",
        dataIndex: "productionOrderNo",
        key: "productionOrderNo",
      },
      {
        title: "车间计划编号",
        dataIndex: "shopPlanNo",
        key: "shopPlanNo",
      },
      {
        title: "合格数量",
        dataIndex: "qualifiedNum",
        key: "qualifiedNum",
        search: false,
      },
      {
        title: "不合格数量",
        dataIndex: "noQualifiedNum",
        key: "noQualifiedNum",
        search: false,
      },
      {
        title: "状态",
        dataIndex: "statusName",
        key: "statusName",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 275,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    columnsc = [
      {
        title: "物料编号",
        dataIndex: "title",
        key: "title",
        search: false,
      },
      {
        title: "物料名称",
        dataIndex: "materieName",
        key: "materieName",
        search: false,
      },
      {
        title: "物料类别",
        dataIndex: "materieTypeName",
        key: "materieTypeName",
        search: false,
      },
      {
        title: "台份量",
        dataIndex: "numberUnits",
        key: "numberUnits",
        search: false,
      },
      {
        title: "预投量（系统计算）",
        dataIndex: "planQuantity",
        key: "planQuantity",
        search: false,
      },
      {
        title: "产出工序",
        dataIndex: "workingProduceName",
        key: "workingProduceName",
        search: false,
      },
      {
        title: "投料工序",
        dataIndex: "workingFeedingName",
        key: "workingFeedingName",
        search: false,
      },
      {
        title: "作为原料",
        dataIndex: "material",
        key: "material",
        valueType: "switch",
        width: 85,
        render: (text, row, _, action) => {
          return row.parentKey != "0" ? (
            <Popconfirm
              title={`${row.isRawMaterial == 1 ? "是否关闭?" : "是否开启?"}`}
              onConfirm={() => {
                doFetch({
                  url: "/ngic-production/omOrderMaterieBomTmp/updateIsRawMaterial",
                  params: {
                    id: row.key,
                    isRawMaterial: row.isRawMaterial == 1 ? 0 : 1,
                  },
                }).then((res) => {
                  if (res.code == "0000") {
                    actionRefs?.current?.reload();
                  }
                });
              }}
              onCancel={() => {}}
              okText="确定"
              cancelText="取消"
              disabled={!getPrem("equipmentSupplier_updatestatus", "ifs")}
            >
              <Switch
                checked={row.isRawMaterial == 1 ? true : false}
                checkedChildren="开启"
                unCheckedChildren="关闭"
                defaultChecked={false}
              />
            </Popconfirm>
          ) : (
            <></>
          );
        },
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 275,
        render: (text, row, _, action) => extraActions(text, row, _, action),
      },
    ],
    columnss = [
      {
        title: "步骤号",
        dataIndex: "stepSort",
        key: "stepSort",
        search: false,
      },
      {
        title: "工序编号",
        dataIndex: "title",
        key: "title",
        search: false,
      },
      {
        title: "工序名称",
        dataIndex: "workingProcedureName",
        key: "workingProcedureName",
        search: false,
      },
      {
        title: "工序类型",
        dataIndex: "workingProcedureTypeName",
        key: "workingProcedureTypeName",
        search: false,
      },
      {
        title: "采集方式",
        dataIndex: "collectionModeName",
        key: "collectionModeName",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 275,
        render: (text, row, _, action) => extraActions(text, row, _, action),
      },
    ],
    steps = [
      {
        title: "基础信息",
        content: (
          <InitForm
            fields={fields}
            onChange={(changedValues, allValues) => {}}
            formRef={formRef}
            actions={(form, submitBtn) => {
              return null;
            }}
            rowCol={0}
          ></InitForm>
        ),
      },
      {
        title: "物料BOM",
        content: (
          <AutoTable
            columns={columnsc}
            path="/ngic-production/omJobOrderMaterieBomTmp/queryTreeList"
            actionRef={actionRefs}
            extraparams={{ jobOrderId: orderId }}
            pagination="false"
            rowKey={"key"}
            expandable={{
              expandedRowKeys: expandedRowKeys ?? [],
              rowExpandable: true,
              onExpand: (expanded, record) => {
                if (expanded) {
                  dispatch({
                    type: "changeExpand",
                    expandedRowKeys: [...expandedRowKeys, record.key],
                  });
                } else {
                  let newKeys = expandedRowKeys.filter(
                    (it) => it != record.key
                  );
                  dispatch({
                    type: "changeExpand",
                    expandedRowKeys: [...newKeys],
                  });
                }
              },
            }}
          ></AutoTable>
        ),
      },
      {
        title: "工艺路线",
        content: (
          <Tabs
            activeKey={tabKey}
            onChange={(key) => {
              dispatch({ type: "changeTabKey", tabKey: key });
            }}
          >
            {tabeTep.map((it, i) => (
              <TabPane tab={it.processLineName} key={it.id}>
                <div style={{ margin: "20px 0" }}>
                  <Row gutter={[16, 10]}>
                    {Object.keys(otherBasic).map((item) => {
                      return (
                        <Coltext
                          label={otherBasic[item]}
                          value={it[item]}
                          key={item}
                        />
                      );
                    })}
                  </Row>
                </div>
                <AutoTable
                  pageextra={extrarenders}
                  columns={columnss}
                  path="/ngic-production/omJobOrderProcessLineStepTmp/queryTreeList"
                  actionRef={actionRefc}
                  pagination="false"
                  rowKey={"key"}
                  extraparams={{ id: tabKey }}
                ></AutoTable>
              </TabPane>
            ))}
          </Tabs>
        ),
      },
    ];
  function extraAction(text, record, _, action) {
    // status  0未锁定 1已锁定 2已撤回 3生产中
    // dataSources  1修改全部   2 修改部分
    let ifs = record.status == 0 || record.status == 2,
      ifsc = record.status == 1,
      ifss = record.status == 3;
    return [
      ifs &&
        getPrem("sysDepartment_save", action, "修改", () => {
          if (record.dataSources == 1) {
            for (let i in addFields) {
              addFields[i].value = record[i];
            }
            dispatch({
              type: "edit",
              fields: addFields,
              curitem: record,
              editType: "mastEdit",
            });
            dispatch({ type: "changeOrderId", orderId: record?.id });
          } else {
            doFetch({
              url: "/ngic-production/umJobOrder/queryDetailById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                let dataSource = res?.data?.data ?? {};
                for (let i in addFields) {
                  addFields[i].value = dataSource[i];
                  if (
                    i == "scheduledProductionNum" ||
                    i == "productionLineId" ||
                    i == "productionDate" ||
                    i == "shiftId" ||
                    i == "groupId" ||
                    i == "description"
                  ) {
                    addFields[i].disabled = false;
                  } else {
                    addFields[i].disabled = true;
                  }
                }
                dispatch({
                  type: "editIssue",
                  fieldsc: addFields,
                  curitem: record,
                });
              }
            });
          }
        }),
      ifs &&
        getPrem("sysDepartment_deleteById", action, "锁定", null, {
          title: "确认锁定该派工单？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umJobOrder/confirmById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
      ifsc &&
        getPrem("sysDepartment_deleteById", action, "撤回", null, {
          title: "确认撤回该派工单？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umJobOrder/withdrawById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
      ifs &&
        getPrem("sysDepartment_deleteById", action, "删除", null, {
          title: "确认删除该派工单？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umJobOrder/deleteById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
      ifsc &&
        getPrem("sysDepartment_deleteById", action, "开工", null, {
          title: "确认开工？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umJobOrder/withStartById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
      ifss &&
        getPrem("sysDepartment_deleteById", action, "完工", null, {
          title: "确认完工？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umJobOrder/withFinishedById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
      ifss && getPrem("sysDepartment_deleteById", action, "打印", () => {}),
    ];
  }
  function extraActions(text, record, index, action) {
    if (currentStep == 1 && record.parentKey == "0") {
      dispatch({ type: "changeExpand", expandedRowKeys: [record.key] });
    }
    return [
      currentStep == 2 &&
        record.parentKey == "0" &&
        getPrem("sysDepartment_deleteById", action, "升序", () => {
          run({
            url: "/ngic-production/omJobOrderProcessLineStepTmp/upDown",
            params: { id: record.key, stepSort: 1 },
          });
        }),
      currentStep == 2 &&
        record.parentKey == "0" &&
        getPrem("sysDepartment_deleteById", action, "降序", () => {
          run({
            url: "/ngic-production/omJobOrderProcessLineStepTmp/upDown",
            params: { id: record.key, stepSort: 2 },
          });
        }),
      ((currentStep == 1 && record.materieType == 2) ||
        record.parentKey == "0") &&
        getPrem("sysDepartment_save", action, "新增", () => {
          if (currentStep == 1) {
            addBomFn({ id: record.key }, record);
          } else if (currentStep == 2) {
            addProcessFn(record, false, "新增工序");
          }
        }),
      currentStep == 1 &&
        record.parentKey != "0" &&
        getPrem("sysDepartment_save", action, "修改", () => {
          if (currentStep == 1) {
            let fieldsc = {
              materieCode: {
                value: null,
                type: "input",
                title: "物料编号",
                name: ["materieCode"],
                required: false,
                disabled: true,
              },
              materieName: {
                value: null,
                type: "input",
                title: "物料名称",
                name: ["materieName"],
                required: false,
                disabled: true,
              },
              materieTypeName: {
                value: null,
                type: "input",
                title: "物料类别",
                name: ["materieTypeName"],
                required: false,
                disabled: true,
              },
              numberUnits: {
                value: null,
                type: "inputnumber",
                title: "台份量",
                name: ["numberUnits"],
                required: true,
              },
              workingProduceId: {
                value: null,
                type: "select",
                title: "产出工序",
                name: ["workingProduceId"],
                required: true,
              },
              workingFeedingId: {
                value: null,
                type: "select",
                title: "投料工序",
                name: ["workingFeedingId"],
                required: true,
              },
            };

            let all = async () => {
              let mark = await doFetch({
                  url: "/ngic-base-business/bmSpecialSet/queryByMark",
                  params: { mark: "materiel_bom" },
                }),
                tem = await doFetch({
                  url: "/ngic-production/omJobOrderMaterieBomTmp/queryUpdateMaterie",
                  params: { id: record.key },
                });
              return {
                markKey: mark?.data?.value,
                temData: tem?.data?.data,
              };
            };
            all().then((res) => {
              const { markKey, temData } = res;
              for (let i in fieldsc) {
                fieldsc[i].value = record[i];
                if (i == "workingProduceId") {
                  fieldsc[i].options = temData?.workingProduceList ?? [];
                  if (record.materieType == 1 || markKey == 2) {
                    fieldsc["workingProduceId"].hides = true;
                  } else {
                    fieldsc["workingProduceId"].hides = false;
                  }
                }
                if (i == "workingFeedingId") {
                  fieldsc[i].options = temData?.workingFeedingList ?? [];
                  if (markKey == 2) {
                    fieldsc["workingFeedingId"].hides = true;
                  } else {
                    fieldsc["workingFeedingId"].hides = false;
                  }
                }
                if (i == "materieCode") {
                  fieldsc[i].value = record.title;
                }
              }
              dispatch({ type: "editBom", fieldsc, curitem: record });
            });
          }
        }),
      ((currentStep == 1 && record.parentKey != "0") || currentStep == 2) &&
        getPrem("sysDepartment_deleteById", action, "删除", null, {
          title:
            currentStep == 1
              ? "确认删除该物料BOM？"
              : record.parentKey == 0
              ? "确认删除该步骤？"
              : "确认删除该工序？",
          onConfirm: () => {
            run({
              url:
                currentStep == 1
                  ? "/ngic-production/omJobOrderMaterieBomTmp/deleteById"
                  : record.parentKey == 0
                  ? "/ngic-production/omJobOrderProcessLineStepTmp/deleteById"
                  : "/ngic-production/omJobOrderProcessLineStepProcedureTmp/deleteById",
              params: { id: record.key },
            });
          },
        }),
    ];
  }
  const next = () => {
    let newStep = currentStep + 1;
    if (currentStep == 0) {
      let editId =
        editType == "mastEdit" ? { jobOrderId: orderId } : { id: orderId };
      formRef.validateFields().then((values) => {
        let newValues = JSON.parse(JSON.stringify(values));
        newValues.productionDate = moment(newValues.productionDate).format(
          "YYYY-MM-DD"
        );
        dispatch({ type: "changeLoading", btnLoading: true });
        doFetch({
          url: "/ngic-production/omJobOrderTmp/save",
          params: { ...newValues, ...editId },
        }).then((res) => {
          if (res.code == "0000") {
            let dataId = res?.data?.data ?? "";
            dispatch({ type: "changeOrderId", orderId: dataId });
            dispatch({ type: "changeValues", fieldsValue: { ...newValues } });
            dispatch({ type: "setCurrent", currentStep: newStep });
            dispatch({ type: "changeLoading", btnLoading: false });
            getExpend(dataId);
          }
        });
      });
    } else {
      dispatch({ type: "setCurrent", currentStep: newStep });
    }
    if (currentStep == 1) {
      doFetch({
        url: "/ngic-production/omJobOrderProcessLineTmp/queryByJobOrderId",
        params: { jobOrderId: orderId },
      }).then((res) => {
        if (res.code == "0000") {
          let data = res?.data?.data ?? {};
          dispatch({ type: "changeTableTep", tabeTep: [data] });
          dispatch({ type: "changeTabKey", tabKey: data?.id ?? "" });
        }
      });
    }
  };
  const prev = () => {
    let newStep = currentStep - 1;
    if (newStep == 0) {
      for (let i in addFields) {
        addFields[i].value = fieldsValue[i];
      }
      dispatch({ type: "changeFields", fields: addFields });
      dispatch({ type: "changeEditType", editType: "prevEdit" });
    }
    if (newStep == 1) {
      getExpend(orderId);
    }
    dispatch({ type: "setCurrent", currentStep: newStep });
  };
  function addBomFn(idparams, record) {
    let all = async () => {
      let mark = await doFetch({
        url: "/ngic-base-business/bmSpecialSet/queryByMark",
        params: { mark: "materiel_bom" },
      });
      return {
        markKey: mark?.data?.value,
      };
    };
    all().then((res) => {
      const { markKey } = res;
      let fieldsc = {
        list: {
          value: [],
          title: "物料",
          type: "checktable",
          col: { span: 24 },
          name: ["list"],
          required: false,
          editable: true,
          columns: [
            {
              title: "物料编号",
              dataIndex: "materieCode",
              key: "materieCode",
            },
            {
              title: "物料名称",
              dataIndex: "materieName",
              key: "materieName",
            },
            {
              title: "物料类别",
              dataIndex: "materieTypeName",
              key: "materieTypeName",
              search: false,
            },
            {
              title: "台份量",
              dataIndex: "numberUnits",
              key: "numberUnits",
              width: 110,
              search: false,
              selectedRender: "InputNumber",
            },
            {
              title: "产出工序",
              dataIndex: "workingProduceId",
              key: "workingProduceId",
              width: 150,
              search: false,
              selectedRender: markKey == 2 ? "" : "Select",
              optionsFields: "workingProduceList",
              renderNull: [
                {
                  name: "materieType",
                  equalvalue: [1],
                },
              ],
            },
            {
              title: "投料工序",
              dataIndex: "workingFeedingId",
              key: "workingFeedingId",
              width: 150,
              search: false,
              selectedRender: markKey == 2 ? "" : "Select",
              optionsFields: "workingFeedingList",
            },
          ],
          path: "/ngic-production/omJobOrderMaterieBomTmp/queryAddMateriePage",
          extraparams: idparams,
          rowKey: "id",
          rowName: "materieName",
        },
      };
      dispatch({ type: "addBom", fieldsc, curitem: record, markKey });
    });
  }
  function addProcessFn(record, isTopRightAdd, title) {
    let fieldsc = {
      procedureList: {
        value: [],
        title: "工序",
        type: "checktable",
        col: { span: 24 },
        name: ["procedureList"],
        required: false,
        editable: false,
        columns: [
          {
            title: "工序编号",
            dataIndex: "workingProcedureCode",
            key: "workingProcedureCode",
          },
          {
            title: "工序名称",
            dataIndex: "workingProcedureName",
            key: "workingProcedureName",
          },
          {
            title: "工序类型",
            dataIndex: "workingProcedureTypeName",
            key: "workingProcedureTypeName",
            search: false,
          },
          {
            title: "采集方式",
            dataIndex: "collectionModeName",
            key: "collectionModeName",
            search: false,
          },
        ],
        path: "/ngic-production/omJobOrderProcessLineStepProcedureTmp/queryAddProcedurePage",
        rowKey: "id",
        rowName: "workingProcedureName",
        extraparams: { id: tabKey },
      },
    };
    dispatch({
      type: "addProcess",
      fieldsc,
      curitem: record,
      isTopRightAdd: isTopRightAdd,
      title,
    });
  }
  let saveData = (values, fn) => {
    let newfields = JSON.parse(JSON.stringify(values));
    //新增&修改
    let params, url;
    if (iftype.val == "editIssue") {
      url = "/ngic-production/umJobOrder/save";
      params = {
        id: curitem.id,
        productionLineId: newfields.productionLineId,
        groupId: newfields.groupId,
        description: newfields.description,
        shiftId: newfields.shiftId,
        scheduledProductionNum: newfields.scheduledProductionNum,
        productionDate: newfields.productionDate,
      };
      doFetch({ url, params }).then((res) => {
        if (res.code == "0000") {
          reload();
          dispatch({ type: "closeBom" });
        }
      });
    } else {
      if (iftype.val == "addBom") {
        newfields.list = newfields.list.map((it) => {
          return {
            materieId: it.id,
            numberUnits: it.numberUnits,
            workingProduceId: it.workingProduceId,
            workingFeedingId: it.workingFeedingId,
          };
        });
        params = {
          ...newfields,
          jobOrderId: orderId,
          parentId: curitem.key,
        };
        url = "/ngic-production/omJobOrderMaterieBomTmp/save";
      } else if (iftype.val == "editBom") {
        params = {
          numberUnits: newfields.numberUnits,
          workingProduceId: newfields.workingProduceId,
          workingFeedingId: newfields.workingFeedingId,
          id: curitem.key,
        };
        url = "/ngic-production/omJobOrderMaterieBomTmp/save";
      } else if (iftype.val == "addProcess") {
        newfields.procedureList = newfields.procedureList.map((it) => {
          return {
            workingProcedureId: it,
          };
        });
        url = "/ngic-production/omJobOrderProcessLineStepTmp/add";
        params = {
          ...newfields,
          jobOrderId: orderId,
          id: iftype.isTopRightAdd ? "" : curitem.key,
          processLineId: tabKey,
        };
      }
      run({ url, params });
    }
  };
  function getExpend(dataId) {
    doFetch({
      url: "/ngic-production/omJobOrderMaterieBomTmp/queryTreeList",
      params: { jobOrderId: dataId },
    }).then((res) => {
      if (res.code == "0000") {
        let dataTree = res?.data?.dataList ?? [];
        dispatch({
          type: "changeExpand",
          expandedRowKeys:
            dataTree?.length > 0
              ? dataTree[0].parentKey == "0"
                ? [dataTree[0].key]
                : []
              : [],
        });
      }
    });
  }
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name}
        pageextra={activeTabKey == "1" ? extrarender : null}
        columns={
          activeTabKey == "1"
            ? columns
            : columns.filter((it) => it.valueType != "option")
        }
        path={
          activeTabKey == "1"
            ? "/ngic-production/umJobOrder/queryList"
            : "/ngic-production/umJobOrder/queryFinishList"
        }
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        tabList={tabList}
        activeTabKey={activeTabKey}
        onTabChange={(key) => {
          dispatch({ type: "changeactiveTabKey", activeTabKey: key });
        }}
      ></AutoTable>

      <Drawer
        title={iftype.title}
        visible={vs}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        style={{ position: "absolute" }}
        getContainer={false}
        maskClosable={false}
      >
        <>
          <div style={{ marginBottom: 15 }}>
            <Steps current={currentStep}>
              {steps.map((item) => (
                <Step key={item.title} title={item.title} />
              ))}
            </Steps>
          </div>
          <div className="steps-content">{steps[currentStep].content}</div>
          <div
            style={{
              display: "flex",
              width: "100%",
              justifyContent: "flex-end",
              marginTop: 15,
            }}
          >
            {currentStep > 0 && (
              <Button style={{ margin: "0 15px" }} onClick={() => prev()}>
                上一步
              </Button>
            )}
            {currentStep < steps.length - 1 && (
              <Button
                loading={btnLoading}
                type="primary"
                onClick={() => next()}
              >
                下一步
              </Button>
            )}
            {currentStep === steps.length - 1 && (
              <Button
                loading={btnLoading}
                type="primary"
                onClick={() => {
                  dispatch({ type: "changeLoading", btnLoading: true });
                  doFetch({
                    url: "/ngic-production/omJobOrderTmp/submit",
                    params: { id: orderId },
                  }).then((res) => {
                    if (res.code == "0000") {
                      reset();
                      dispatch({ type: "changeLoading", btnLoading: false });
                    }
                  });
                }}
              >
                提交
              </Button>
            )}
          </div>
        </>
      </Drawer>
      <Drawer
        title={iftype.title}
        visible={visible}
        onClose={() => dispatch({ type: "closeBom" })}
        footer={false}
        destroyOnClose={true}
        width={900}
        style={{ position: "absolute" }}
        getContainer={false}
        maskClosable={false}
      >
        <InitForm
          fields={fieldsc}
          submitData={(values, fn) => {
            saveData(values, fn);
          }}
          onChange={(changedValues, allValues) => {}}
          submitting={loading || !visible}
        ></InitForm>
      </Drawer>
      <Drawer
        title={iftype.title}
        visible={schedulingVisible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        style={{ position: "absolute" }}
        getContainer={false}
        maskClosable={false}
      >
        {iftype.val == "scheduling" ? (
          <Scheduling reset={reset} schedulingVisible={schedulingVisible} />
        ) : (
          <Setsort />
        )}
      </Drawer>
      <Details
        title="派工单详情"
        visible={detailsVisible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        bottomNode={
          <Card
            title={`工艺路线信息（所属工厂：${detailStepData.factoryName} | 所属车间：${detailStepData.shopName}）`}
            bordered={false}
            style={{ marginBottom: 16 }}
            bodyStyle={{ padding: "16px 10px" }}
          >
            <div className="gongyiStep">
              <Steps direction="vertical">
                {detailStepData?.jobOrderProcessLineStepList?.map((it, i) => {
                  return (
                    <Step
                      disabled={true}
                      key={i}
                      title={
                        <div style={{ width: "100%", display: "flex" }}>
                          <div className={styles.stepTitle}>
                            <Tooltip title={`步骤${i + 1}`}>
                              <span>{`步骤${i + 1}`}</span>
                            </Tooltip>
                          </div>
                        </div>
                      }
                      description={
                        it?.processLineStepProcedureList && (
                          <div style={{ width: "100%" }}>
                            <Row gutter={[12, 12]}>
                              {it?.processLineStepProcedureList?.map(
                                (item, j) => {
                                  return (
                                    <Col span={8} key={j}>
                                      <div
                                        style={{
                                          padding: 12,
                                          border: "1px solid #d9d9d9",
                                        }}
                                      >
                                        <div
                                          style={{
                                            display: "flex",
                                            flexDirection: "column",
                                            justifyContent: "center",
                                          }}
                                        >
                                          <Tooltip
                                            title={`工序编号：${item.workingProcedureCode}`}
                                          >
                                            <div
                                              className={styles.one}
                                              style={{ marginBottom: 12 }}
                                            >
                                              工序编号：
                                              {item.workingProcedureCode}
                                            </div>
                                          </Tooltip>
                                          <Tooltip
                                            title={`工序名称：${item.workingProcedureName}`}
                                          >
                                            <div className={styles.one}>
                                              工序名称：
                                              {item.workingProcedureName}
                                            </div>
                                          </Tooltip>
                                        </div>
                                      </div>
                                    </Col>
                                  );
                                }
                              )}
                            </Row>
                          </div>
                        )
                      }
                    />
                  );
                })}
              </Steps>
            </div>
          </Card>
        }
        {...detail}
      ></Details>
    </div>
  );
};
export default Dispatchorder;
