import React, { useEffect, useRef, useState, useReducer } from "react";
import { Card, Modal, Button, Divider, message, Form } from "antd";
import { useRequest } from "umi";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import defaultFields from "./fields";
import { doFetch } from "@/utils/doFetch";
import { bmNoTypeAll, bmNoType } from "@/services/platform";
import DrawInitForm from "@/components/DrawInitForm";

const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  bmNoTypeData: [],
};
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 "changeFields":
      newState = {
        ...state,
        fields: action.fields,
      };
      break;
    case "changeBmNoType":
      newState = {
        ...state,
        bmNoTypeData: action.bmNoTypeData,
      };
      break;
    case "close":
      newState = {
        ...state,
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
      };
      break;
  }

  return newState;
}
let Rule = (props) => {
  let actionRef = useRef(),
    [formRef] = Form.useForm();
  function reload() {
    actionRef?.current?.reload();
  }
  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, bmNoTypeData } = state,
    columns = [
      {
        title: "编号大类",
        dataIndex: "noTypeName",
        key: "noTypeName",
      },
      {
        title: "编号子类",
        dataIndex: "noSunName",
        key: "noSunName",
      },
      {
        title: "预览",
        dataIndex: "ruleNames",
        key: "ruleNames",
        search: false,
      },
      {
        title: "操作",
        valueType: "option",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        width: 135,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ];

  useEffect(() => {
    doFetch({ url: "/ngic-base-business/bmNoType/querySelectAll" }).then(
      (res) => {
        if (res.code == "0000") {
          let dataList = res?.data?.dataList ?? [];
          dispatch({ type: "changeBmNoType", bmNoTypeData: dataList });
        }
      }
    );
  }, [props.route]);

  function extraAction(text, record, _, action) {
    return [
      getPrem("bmNumberRule_save", action, "修改", () => {
        doFetch({
          url: "/ngic-base-business/bmMainNumberRule/queryDetails",
          params: { id: record.id },
        }).then((res) => {
          let row = res?.data?.data;
          for (let i in defaultFields) {
            defaultFields[i].value = row[i];
            if (i == "noTypeId") {
              defaultFields[i].disabled = true;
              defaultFields[i].options.database = bmNoTypeAll;
            }
            if (i == "nrList") {
              let reshow = {
                value: row[i].filter(
                  (it) => it.noRuleCode != "increasing_order"
                ),
                other:
                  row[i].filter(
                    (it) => it.noRuleCode == "increasing_order"
                  )[0] || {},
              };
              reshow.other.increaseList = reshow.other.increaseList.map(
                (it) => {
                  return reshow.value.filter((item) => item.sort == it)[0].id;
                }
              );
              reshow.other.sort =
                reshow.other.sort == 1
                  ? reshow.other.sort
                  : reshow.other.sort - 1;

              defaultFields[i].value = reshow;
              defaultFields[i].extraparams = { noTypeId: record.noTypeId };
            }
            if (i == "noSunName") {
              let filterData = bmNoTypeData.filter(
                (it) => it.value == row["noTypeId"]
              );
              if (filterData.length > 0) {
                defaultFields[i].hides =
                  filterData[0].isSun == 1 ? false : true;
              } else {
                defaultFields[i].hides = false;
              }
            }
          }
          dispatch({ type: "edit", fields: defaultFields, curitem: row });
        });
      }),
      getPrem("bmNumberRule_deleteByNoTypeId", action, "删除", null, {
        title: "确认删除该编号规则?",
        onConfirm: () => {
          run({
            url: "/ngic-base-business/bmMainNumberRule/deleteById",
            params: { id: record.id },
          });
        },
      }),
    ];
  }

  let saveData = (values, fn) => {
    let newvalues = JSON.parse(JSON.stringify(values));
    let nrList = newvalues.nrList;
    let submitnolist = nrList.value,
      other = nrList.other;

    if (other.sort) {
      submitnolist.splice(other.sort, 0, other);
    } else {
      submitnolist.push(other);
    }

    submitnolist = submitnolist.map((it, i) => {
      return {
        ...it,
        sort: i + 1,
      };
    });

    submitnolist = submitnolist.map((it, i) => {
      if (it.noRuleCode == "increasing_order") {
        it.increaseList = it.increaseList.map((item) => {
          return submitnolist.filter((itemz) => itemz.id == item)[0].sort;
        });
      }
      return {
        ...it,
      };
    });

    let newfields = {
      ...newvalues,
      nrList: submitnolist,
    };

    let difrid = iftype.val == "edit" ? { id: curitem.id } : {};
    run({
      url: "/ngic-base-business/bmMainNumberRule/save",
      params: { ...newfields, ...difrid },
    });
  };

  let extra = (
    <Button
      disabled={!getPrem("bmNumberRule_save", "ifs")}
      type="primary"
      onClick={() => {
        for (let i in defaultFields) {
          defaultFields[i].value = null;
          defaultFields[i].disabled = false;
          if (i == "nrList") {
            defaultFields[i].extraparams = { noTypeId: "" };
          }
          if (i == "noTypeId") {
            defaultFields[i].options = {
              database: bmNoType,
              params: {},
            };
          }
        }
        dispatch({ type: "add", fields: defaultFields });
      }}
    >
      新增
    </Button>
  );
  return (
    <div>
      <AutoTable
        columns={columns}
        actionRef={actionRef}
        pagetitle={props.route.name}
        pageextra={extra}
        refreshDep={[bmNoTypeData]}
        path="/ngic-base-business/bmMainNumberRule/queryList"
      ></AutoTable>

      <DrawInitForm
        title={iftype.title}
        visible={vs}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        fields={fields}
        submitData={(values) => {
          saveData(values);
        }}
        onChange={(changedValues, allValues) => {
          //联动操作
          for (let i in changedValues) {
            if (i == "noTypeId") {
              for (let j in fields) {
                if (j == "nrList") {
                  fields[j].extraparams = { noTypeId: changedValues[i] };
                  fields[j].value = {
                    value: allValues.nrList?.value.map((it) => ({
                      ...it,
                      noRuleCode: "",
                    })),
                    other: {
                      ...allValues.nrList?.other,
                      noRuleCode: "",
                    },
                  };
                }
                if (j == "noSunName") {
                  let filterData = bmNoTypeData.filter(
                    (it) => it.value == changedValues[i]
                  );
                  if (filterData.length > 0) {
                    defaultFields[j].hides =
                      filterData[0].isSun == 1 ? false : true;
                  } else {
                    fields[j].hides = false;
                  }
                }
              }
              formRef.setFieldsValue({ nrList: fields["nrList"].value });
              dispatch({ type: "changeFields", fields });
            }
          }
        }}
        submitting={loading || !vs}
        width={"100%"}
        formRef={formRef}
      ></DrawInitForm>
    </div>
  );
};

export default Rule;