import React, { useEffect, useRef, useReducer } from "react";
import {
  Button,
  Tooltip,
  Row,
  Divider,
  Drawer,
  Table,
  Col,
  Steps,
  Card,
} from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import { useRequest } from "umi";
import defaultFields from "./fields";
import { doFetch } from "@/utils/doFetch";
import Details from "@/components/Details";
import { gongyiDetail } from "@/utils/detailTotalCard";
import Coltext from "@/components/Coltext";
import InitForm from "@/components/InitForm";
import styles from "./index.less";
import {
  PlusSquareOutlined,
  MinusSquareOutlined,
  MinusCircleOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
} from "@ant-design/icons";
const { Step } = Steps;
const initState = {
    vs: false,
    fields: {},
    iftype: {},
    curitem: {},
    detail: {
      dataSource: {},
      totalCard: [],
    },
    visible: false,
    process: [],
    rightSelectedRows: [],
    current: 0,
    stepData: [
      {
        processLineStepProcedureList: [],
        stepSort: 0,
      },
    ],
    detailStepData: [],
  },
  otherBasic = {
    workingProcedureNames: "步骤工序",
  };
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 "edit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "编辑工艺路线",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
      };
      break;
    case "design":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "工艺设计",
          val: type,
        },
        fields: {},
        curitem: action.curitem,
        process: action.process,
        stepData: action.stepData,
      };
      break;
    case "see":
      newState = {
        ...state,
        detail: {
          dataSource: action.dataSource,
          totalCard: [...gongyiDetail],
        },
        detailStepData: action.detailStepData,
        visible: true,
      };
      break;
    case "changeProcess":
      newState = {
        ...state,
        process: action.process,
      };
      break;
    case "changeRightSelect":
      newState = {
        ...state,
        rightSelectedRows: action.rightSelectedRows,
      };
      break;
    case "changeCurrent":
      newState = {
        ...state,
        current: action.current,
      };
      break;
    case "changeStep":
      newState = {
        ...state,
        stepData: action.stepData,
      };
      break;
    case "close":
      newState = {
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        detail: {
          dataSource: {},
          totalCard: [],
        },
        visible: false,
        process: [],
        rightSelectedRows: [],
        current: 0,
        stepData: [
          {
            processLineStepProcedureList: [],
            stepSort: 0,
          },
        ],
        detailStepData: [],
      };
      break;
  }

  return newState;
}

const Gongyi = (props) => {
  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          reload();
          dispatch({ type: "close" });
        }
      },
    }),
    [state, dispatch] = useReducer(reducer, initState),
    {
      vs,
      fields,
      iftype,
      curitem,
      detail,
      visible,
      process,
      rightSelectedRows,
      current,
      stepData,
      detailStepData,
    } = state,
    columns = [
      {
        title: "工艺路线编号",
        dataIndex: "processLineCode",
        key: "processLineCode",
      },
      {
        title: "工艺路线名称",
        dataIndex: "processLineName",
        key: "processLineName",
        render: (_, row) => {
          return (
            <Tooltip title={row.processLineName}>
              <a
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-workmanship/pmProcessLine/queryDetailById",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {};
                      dispatch({
                        type: "see",
                        dataSource,
                        detailStepData:
                          dataSource?.processLineStepDtoList ?? [],
                      });
                    }
                  });
                }}
              >
                {row.processLineName}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "所属工厂",
        dataIndex: "factoryName",
        key: "factoryName",
      },
      {
        title: "所属车间",
        dataIndex: "shopName",
        key: "shopName",
      },
      {
        title: "工艺路线类型",
        dataIndex: "processLineTypeName",
        key: "processLineTypeName",
        options: [
          {
            label: "常规",
            value: 1,
          },
          {
            label: "返工",
            value: 2,
          },
        ],
        valueType: "select",
        formItemProps: {
          name: "processLineType",
        },
      },
      {
        title: "能力",
        dataIndex: "capacity",
        key: "capacity",
        search: false,
      },
      {
        title: "描述",
        dataIndex: "remark",
        key: "remark",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 255,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    columnsc = [
      {
        title: "工序编号",
        dataIndex: "workingProcedureCode",
        key: "workingProcedureCode",
        search: false,
        ellipsis: true,
      },
      {
        title: "工序名称",
        dataIndex: "workingProcedureName",
        key: "workingProcedureName",
        search: false,
        ellipsis: true,
      },
      {
        title: "工序类型",
        dataIndex: "workingProcedureTypeName",
        key: "workingProcedureTypeName",
        search: false,
        ellipsis: true,
      },
      {
        title: "采集方式",
        dataIndex: "collectionModeName",
        key: "collectionModeName",
        search: false,
        ellipsis: true,
      },
    ];
  function extraAction(text, record, _, action) {
    return [
      getPrem("sysDepartment_save", action, "修改", () => {
        doFetch({
          url: "/ngic-workmanship/pmProcessLine/queryDetailById",
          params: { id: record.id },
        }).then((res) => {
          if (res.code == "0000") {
            let data = res?.data?.data ?? {};
            for (let i in defaultFields) {
              defaultFields[i].value = record[i];
              if (i == "factoryId" || i == "shopId") {
                if (data?.processLineStepDtoList?.length > 0) {
                  defaultFields[i].disabled = true;
                } else {
                  defaultFields[i].disabled = false;
                }
              }
            }
            let newData =
                data?.processLineStepDtoList?.map((it) => {
                  let itemProcessLineStepProcedure =
                    it.processLineStepProcedureList.map((item) => {
                      return item.workingProcedureName;
                    });
                  return itemProcessLineStepProcedure.join(",");
                }) ?? [],
              workingProcedureNames = newData.join("—>");

            dispatch({
              type: "edit",
              fields: defaultFields,
              curitem: { ...data, workingProcedureNames },
            });
          }
        });
      }),
      getPrem("sysDepartment_save", action, "工艺设计", () => {
        let all = async () => {
          let detail = await doFetch({
              url: "/ngic-workmanship/pmProcessLine/queryDetailById",
              params: { id: record.id },
            }),
            table = await doFetch({
              url: "/ngic-workmanship/workingProcedure/querySelectedList",
              params: { shopId: record.shopId, processLineId: record.id },
            });
          return {
            detailData: detail?.data?.data ?? {},
            tableData: table?.data?.dataList ?? [],
          };
        };
        all().then((res) => {
          let data = res?.detailData ?? {};
          dispatch({
            type: "design",
            curitem: record,
            process: res?.tableData,
            stepData: data?.processLineStepDtoList ?? [
              {
                processLineStepProcedureList: [],
                stepSort: 0,
              },
            ],
          });
        });
      }),
      getPrem("sysDepartment_deleteById", action, "删除", null, {
        title: "确认删除该工艺路线?",
        onConfirm: () => {
          run({
            url: "/ngic-workmanship/pmProcessLine/deleteById",
            params: { id: record.id },
          });
        },
      }),
    ];
  }
  let saveData = (values, fn) => {
    let params, url;
    if (iftype.val == "design") {
      let processLineStepList = [];
      stepData?.map((it) => {
        if (it.processLineStepProcedureList.length > 0) {
          let el = {
            stepSort: it.stepSort,
            lineStepProcedureList: it.processLineStepProcedureList.map(
              (item) => item.id
            ),
          };
          processLineStepList.push(el);
        }
      });
      for (let i = 0; i < processLineStepList.length; i++) {
        processLineStepList[i].stepSort = i;
      }
      url = "/ngic-workmanship/pmProcessLineStep/save";
      params = {
        processLineId: curitem.id,
        processLineStepList,
      };
    } else {
      let newfields = JSON.parse(JSON.stringify(values)),
        difrid = iftype.val == "edit" ? { id: curitem.id } : {};
      url = "/ngic-workmanship/pmProcessLine/save";
      params = {
        ...newfields,
        ...difrid,
      };
    }
    run({ url, params });
  };
  let extrarender = [
    <Button
      disabled={!getPrem("sysDepartment_save", "ifs")}
      type="primary"
      onClick={() => {
        for (let i in defaultFields) {
          defaultFields[i].value = null;
          defaultFields[i].disabled = false;
        }
        dispatch({ type: "add", fields: defaultFields });
      }}
    >
      新增
    </Button>,
  ];
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        path="/ngic-workmanship/pmProcessLine/queryList"
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
      ></AutoTable>
      {vs && iftype.val == "design" && (
        <div>
          <Button
            type="primary"
            size="large"
            loading={loading || !vs}
            style={{
              position: "absolute",
              left: 14,
              bottom: 6,
              zIndex: 9999,
              width: "52%",
            }}
            onClick={() => {
              saveData();
            }}
          >
            提交
          </Button>

          <div
            style={{
              position: "absolute",
              right: 14,
              bottom: 0,
              zIndex: 9999,
              width: "45%",
              border: "1px solid #1890ff",
              padding: 10,
            }}
          >
            <div
              style={{
                marginBottom: 12,
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <span>工序</span>
              <Button
                onClick={() => {
                  let newStep = JSON.parse(JSON.stringify(stepData)),
                    rightSelectedRowsIds = rightSelectedRows?.map(
                      (item) => item.id
                    );
                  for (let i = 0; i < newStep.length; i++) {
                    let it = newStep[i];
                    if (it.stepSort == current) {
                      it.processLineStepProcedureList =
                        it?.processLineStepProcedureList
                          .filter(
                            (item) =>
                              rightSelectedRowsIds.indexOf(item.id) == -1
                          )
                          .concat(rightSelectedRows);
                    }
                  }
                  let newProcess = process.filter(
                    (it) => rightSelectedRowsIds.indexOf(it.id) == -1
                  );
                  dispatch({ type: "changeStep", stepData: newStep });
                  dispatch({ type: "changeProcess", process: newProcess });
                  dispatch({
                    type: "changeRightSelect",
                    rightSelectedRows: [],
                  });
                }}
                disabled={
                  process.length == 0 ||
                  rightSelectedRows.length == 0 ||
                  stepData.length == 0
                }
                type="primary"
              >
                添加到工艺工序
              </Button>
            </div>
            <Table
              columns={columnsc}
              dataSource={process}
              pagination={false}
              rowSelection={{
                selectedRowKeys: rightSelectedRows.map((it) => it.id),
                onChange: (selectedRowKeys, selectedRows) => {
                  dispatch({
                    type: "changeRightSelect",
                    rightSelectedRows: selectedRows,
                  });
                },
              }}
              rowKey="id"
              scroll={{
                y: 700,
              }}
            />
          </div>
        </div>
      )}
      <Drawer
        title={iftype.title}
        visible={vs}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        style={{ position: "absolute" }}
        getContainer={false}
        maskClosable={false}
      >
        {iftype.val == "edit" && (
          <>
            <Row gutter={[16, 10]}>
              {Object.keys(otherBasic).map((it) => {
                return (
                  <Coltext
                    label={otherBasic[it]}
                    value={curitem[it]}
                    key={it}
                    col={{ span: 24 }}
                  />
                );
              })}
            </Row>
            <Divider />
          </>
        )}
        {iftype.val == "design" ? (
          <div style={{ height: "95%", width: "52%" }}>
            <div className="gongyiStep">
              <Steps
                direction="vertical"
                current={current}
                onChange={(c) => {
                  dispatch({ type: "changeCurrent", current: c });
                }}
              >
                {stepData?.map((it, i) => {
                  return (
                    <Step
                      key={i}
                      title={
                        <div style={{ width: "100%", display: "flex" }}>
                          <div className={styles.stepTitle}>
                            <Tooltip title={`步骤${i + 1}`}>
                              <span>{`步骤${i + 1}`}</span>
                            </Tooltip>
                          </div>
                          <Tooltip title="增加步骤">
                            <Button
                              onClick={(event) => {
                                event.stopPropagation();
                                let newStepData = JSON.parse(
                                    JSON.stringify(stepData)
                                  ),
                                  addIndex = newStepData
                                    .map((el) => el.stepSort)
                                    .indexOf(i);
                                let addata = [
                                    {
                                      processLineStepProcedureList: [],
                                      stepSort: i + 1,
                                    },
                                  ],
                                  newCurrent = i + 1;
                                let firstArr = newStepData.slice(
                                    0,
                                    addIndex + 1
                                  ),
                                  lastArr = newStepData.slice(
                                    addIndex + 1,
                                    newStepData.length
                                  );
                                if (lastArr.length) {
                                  for (let j = 0; j < lastArr.length; j++) {
                                    lastArr[j].stepSort =
                                      lastArr[j].stepSort + 1;
                                  }
                                }
                                let allArr = firstArr
                                  .concat(addata)
                                  .concat(lastArr);
                                dispatch({
                                  type: "changeStep",
                                  stepData: allArr,
                                });
                                dispatch({
                                  type: "changeCurrent",
                                  current: newCurrent,
                                });
                              }}
                              type="link"
                              icon={<PlusSquareOutlined />}
                            ></Button>
                          </Tooltip>
                          {it?.processLineStepProcedureList?.length == 0 && (
                            <Tooltip title="删除步骤">
                              <Button
                                onClick={(event) => {
                                  event.stopPropagation();
                                  let newStepData = stepData.filter(
                                    (it) => it.stepSort != i
                                  );
                                  let newStepArr = newStepData.map(
                                      (el, index) => {
                                        el.stepSort = index;
                                        return el;
                                      }
                                    ),
                                    newCurrent = i > 1 ? i - 1 : 0;
                                  dispatch({
                                    type: "changeStep",
                                    stepData: newStepArr,
                                  });
                                  dispatch({
                                    type: "changeCurrent",
                                    current: newCurrent,
                                  });
                                }}
                                type="link"
                                icon={<MinusSquareOutlined />}
                              ></Button>
                            </Tooltip>
                          )}
                          {i != 0 &&
                            it?.processLineStepProcedureList?.length != 0 && (
                              <Tooltip title="升序">
                                <Button
                                  onClick={(event) => {
                                    event.stopPropagation();
                                    let el = stepData[i];
                                    el.stepSort = el.stepSort - 1;
                                    stepData[i - 1].stepSort =
                                      stepData[i - 1].stepSort + 1;
                                    stepData?.sort((a, b) => {
                                      return a.stepSort - b.stepSort;
                                    });
                                    dispatch({
                                      type: "changeStep",
                                      stepData: stepData,
                                    });
                                    dispatch({
                                      type: "changeCurrent",
                                      current: el.stepSort,
                                    });
                                  }}
                                  type="link"
                                  icon={<ArrowUpOutlined />}
                                ></Button>
                              </Tooltip>
                            )}
                          {i != stepData.length - 1 &&
                            it?.processLineStepProcedureList?.length != 0 && (
                              <Tooltip title="降序">
                                <Button
                                  onClick={(event) => {
                                    event.stopPropagation();
                                    let el = stepData[i];
                                    el.stepSort = el.stepSort + 1;
                                    stepData[i + 1].stepSort =
                                      stepData[i + 1].stepSort - 1;
                                    stepData?.sort((a, b) => {
                                      return a.stepSort - b.stepSort;
                                    });
                                    dispatch({
                                      type: "changeStep",
                                      stepData: stepData,
                                    });
                                    dispatch({
                                      type: "changeCurrent",
                                      current: el.stepSort,
                                    });
                                  }}
                                  type="link"
                                  icon={<ArrowDownOutlined />}
                                ></Button>
                              </Tooltip>
                            )}
                        </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: 8,
                                          border: "1px solid #d9d9d9",
                                          overflow: "hidden",
                                          width: "100%",
                                        }}
                                      >
                                        <div
                                          style={{ width: 30, float: "right" }}
                                        >
                                          <Tooltip title="删除工序">
                                            <Button
                                              onClick={(event) => {
                                                event.stopPropagation();
                                                let newProcessLineStepProcedureList =
                                                  it.processLineStepProcedureList?.filter(
                                                    (el) => el.id != item.id
                                                  );
                                                let newStepData = stepData.map(
                                                  (el) => {
                                                    if (el.stepSort == i) {
                                                      el.processLineStepProcedureList =
                                                        newProcessLineStepProcedureList;
                                                    }
                                                    return el;
                                                  }
                                                );
                                                dispatch({
                                                  type: "changeStep",
                                                  stepData: newStepData,
                                                });
                                                dispatch({
                                                  type: "changeProcess",
                                                  process: [...process, item],
                                                });
                                                dispatch({
                                                  type: "changeCurrent",
                                                  current: i,
                                                });
                                              }}
                                              type="link"
                                              icon={<MinusCircleOutlined />}
                                            ></Button>
                                          </Tooltip>
                                        </div>
                                        <div
                                          style={{
                                            display: "flex",
                                            flexDirection: "column",
                                            justifyContent: "center",
                                            float: "none",
                                          }}
                                        >
                                          <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>
          </div>
        ) : (
          <InitForm
            fields={fields}
            submitData={(values, fn) => {
              saveData(values, fn);
            }}
            onChange={(changedValues, allValues) => {}}
            submitting={loading || !vs}
          ></InitForm>
        )}
      </Drawer>
      <Details
        title="工艺路线详情"
        visible={visible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        bottomNode={
          <Card
            title="工艺工序"
            bordered={false}
            style={{ marginBottom: 16 }}
            bodyStyle={{ padding: "16px 10px" }}
          >
            <div className="gongyiStep">
              <Steps direction="vertical">
                {detailStepData?.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 Gongyi;