import React, { memo, useEffect, useRef, useState, useReducer } from "react";
import {
  Image,
  Divider,
  Menu,
  Dropdown,
  Button,
  Modal,
  Row,
  Col,
  Tooltip,
  Drawer,
  Form,
  Input,
  message,
  Typography,
} from "antd";
import { connect, useRequest } from "umi";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import InitForm from "@/components/InitForm";
import { doFetch } from "@/utils/doFetch";
import { tableField } from "./fields";
import moment from "moment";
import {
  factorySelect,
  zuzhi,
  allDepartment,
  allShop,
  depart,
  selectionBoxAll,
  roleList,
  currentUserList,
} from "@/services/system";
const { TextArea } = Input,
  { Paragraph } = Typography;

const initState = {
    vs: false,
    tableFields: {},
    iftype: {},
    tableData: [],
    hidesTitle: true,
    hidesContent: true,
    formFields: {},
    tableLoading: false,
    variableVisible: false,
    variableExtraparams: "",
  },
  sendToArr = [
    {
      label: "可操作人员",
      value: 1,
    },
    {
      label: "创建人",
      value: 2,
    },
    {
      label: "（上个通知人员）上级领导",
      value: 3,
    },
    {
      label: "选择角色",
      value: 4,
    },
    {
      label: "选择人员",
      value: 5,
    },
  ],
  unitArr = [
    {
      label: "分钟",
      value: 1,
    },
    {
      label: "小时",
      value: 2,
    },
    {
      label: "天",
      value: 3,
    },
  ],
  sendProcessArr = [
    {
      label: "一级通知",
      value: 1,
    },
    {
      label: "二级通知",
      value: 2,
    },
    {
      label: "三级通知",
      value: 3,
    },
    {
      label: "四级通知",
      value: 4,
    },
    {
      label: "五级通知",
      value: 5,
    },
    {
      label: "六级通知",
      value: 6,
    },
    {
      label: "七级通知",
      value: 7,
    },
    {
      label: "八级通知",
      value: 8,
    },
  ];
function reducer(state, action) {
  if (action.type == "add") {
    return {
      ...state,
      vs: true,
      tableFields: { ...action.tableFields },
      iftype: {
        val: "add",
        title: "新增基础设置",
        id: "",
      },
    };
  } else if (action.type == "edit") {
    return {
      ...state,
      vs: true,
      tableFields: { ...action.tableFields },
      iftype: {
        val: "edit",
        title: "修改基础设置",
        id: action.curitem.id,
      },
    };
  } else if (action.type == "changeHideTitle") {
    return {
      ...state,
      hidesTitle: action.hidesTitle,
    };
  } else if (action.type == "changeHideContent") {
    return {
      ...state,
      hidesContent: action.hidesContent,
    };
  } else if (action.type == "changeFormFields") {
    return {
      ...state,
      formFields: { ...action.formFields },
    };
  } else if (action.type == "start") {
    return {
      ...state,
      formFields: { ...action.formFields },
      tableData: [...action.tableData],
    };
  } else if (action.type == "changeTableFields") {
    return {
      ...state,
      tableFields: { ...action.tableFields },
    };
  } else if (action.type == "changeTableData") {
    return {
      ...state,
      tableData: [...action.tableData],
      vs: false,
      tableLoading: false,
    };
  } else if (action.type == "changeLoading") {
    return {
      ...state,
      tableLoading: true,
    };
  } else if (action.type == "changeShown") {
    return {
      ...state,
      shown: action.shown,
    };
  } else if (action.type == "openVariable") {
    return {
      ...state,
      variableVisible: true,
      variableExtraparams: action.variableExtraparams,
    };
  } else if (action.type == "close") {
    return {
      ...state,
      vs: false,
      iftype: {},
      tableFields: {},
      variableVisible: false,
      variableExtraparams: "",
    };
  }
}

const Variable = (props) => {
  const { businessMsgSceneId, dispatch } = props;
  return (
    <div>
      <AutoTable
        withCard={false}
        columns={[
          {
            title: "变量名",
            dataIndex: "variableName",
            key: "variableName",
            width: 120,
          },
          {
            title: "变量代码",
            dataIndex: "variableCode",
            key: "variableCode",
            search: false,
          },
          {
            title: "复制",
            valueType: "option",
            search: false,
            render: (_, row) => {
              return (
                <Paragraph
                  copyable={{
                    text: row.variableCode,
                    onCopy: () => {
                      dispatch({ type: "close" });
                    },
                  }}
                >
                  复制
                </Paragraph>
              );
            },
          },
        ]}
        bordered={false}
        path="/ngic-base-business/paBusinessMsgSceneVariable/queryPageBySceneId"
        extraparams={{ businessMsgSceneId }}
        x={"100%"}
      ></AutoTable>
    </div>
  );
};
const Formpage = (props) => {
  const { rowMessage, reset, iftypeParent } = props;
  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  useEffect(() => {
    if (iftypeParent.val == "add") {
      for (let i in fields) {
        fields[i].hides = false;
        fields[i].value = null;
      }
    } else if (iftypeParent.val == "edit") {
      let database = getdatabase(rowMessage["fitField"]);
      for (let i in fields) {
        fields[i].value = rowMessage[i];
        if (i == "sendMethodType") {
          showTitleorContent(rowMessage[i]);
          form.setFieldsValue({
            sendTitle: rowMessage.sendTitle,
            sendContent: rowMessage.sendContent,
          });
        }
        if (i == "fieldId" && rowMessage["fitField"] == 1) {
          fields[i].hides = true;
        } else if (i == "fieldId" && rowMessage["fitField"] != 1) {
          fields[i].hides = false;
          fields[i].options = {
            database,
            params: {},
          };
        }
      }
    }
    dispatch({
      type: "start",
      formFields: { ...fields },
      tableData: iftypeParent.val == "add" ? [] : rowMessage?.detailList,
    });
  }, [fields]);

  const { fields } = props,
    [form] = Form.useForm(),
    [forms] = Form.useForm(),
    [tableFormRef] = Form.useForm(),
    [state, dispatch] = useReducer(reducer, initState),
    {
      vs,
      tableFields,
      iftype,
      tableData,
      hidesTitle,
      hidesContent,
      formFields,
      tableLoading,
      variableVisible,
      shown,
      variableExtraparams,
    } = state,
    columns = [
      {
        title: "推送流程",
        dataIndex: "sendProcessName",
        key: "sendProcessName",
        search: false,
      },
      {
        title: "推送对象",
        dataIndex: "sendToName",
        key: "sendToName",
        search: false,
      },
      {
        title: "选择对象",
        dataIndex: "targetNames",
        key: "targetNames",
        search: false,
      },
      {
        title: "初始触发时长",
        dataIndex: "initialTime",
        key: "initialTime",
        search: false,
      },
      {
        title: "初始触发时长单位",
        dataIndex: "initialUnitName",
        key: "initialUnitName",
        search: false,
      },
      {
        title: "间隔时长",
        dataIndex: "intervalTime",
        key: "intervalTime",
        search: false,
      },
      {
        title: "间隔时长单位",
        dataIndex: "intervalUnitName",
        key: "intervalUnitName",
        search: false,
      },
      {
        title: "触发次数",
        dataIndex: "sendNum",
        key: "sendNum",
        search: false,
      },
      {
        title: "操作",
        valueType: "option",
        width: 150,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          reset && reset();
        }
      },
    });
  let extrarender = [
    <Button
      size={"middle"}
      type="primary"
      onClick={() => {
        for (let i in tableField) {
          tableField[i].value = null;
          if (i == "targetIdList") {
            tableField[i].hides = true;
            tableField[i].value = [];
          }
          if (i == "initialTime") {
            tableField[i].value = 0;
          }
          if (i == "intervalTime") {
            tableField[i].value = 1;
          }
          if (i == "sendNum") {
            tableField[i].value = 1;
          }
        }
        dispatch({ type: "add", tableFields: tableField });
      }}
    >
      新增
    </Button>,
  ];
  function extraAction(text, record, _, action) {
    return (
      <div>
        {getPrem(true, null, "修改", () => {
          for (let j in tableField) {
            tableField[j].value = record[j];
            if (j == "targetIdList") {
              if (record.sendTo != 4 && record.sendTo != 5) {
                tableField[j].hides = true;
              } else {
                let database = getformdatabase(record.sendTo);
                tableField[j].hides = false;
                tableField[j].options = {
                  database,
                  params: {},
                };
              }
            }
            dispatch({
              type: "edit",
              tableFields: tableField,
              curitem: record,
            });
          }
        })}
        <Divider type="vertical" />
        {getPrem(true, "red", "删除", null, {
          title: "确认删除该基础配置？",
          onConfirm: () => {
            let newData = tableData.filter((it) => it.id != record.id);
            dispatch({ type: "changeTableData", tableData: newData });
          },
        })}
      </div>
    );
  }
  let saveData = (values, fn) => {
      dispatch({ type: "changeLoading" });
      const {
        sendTo,
        targetIdList,
        sendProcess,
        initialUnit,
        initialTime,
        intervalTime,
        intervalUnit,
        sendNum,
      } = values;
      let targetNames = [];
      let all = async () => {
        if (sendTo == 4) {
          let data = await roleList({});
          return {
            newArr: data?.data?.dataList || [],
          };
        } else if (sendTo == 5) {
          let data = await currentUserList({});
          return {
            newArr: data?.data?.dataList || [],
          };
        } else {
          return {
            newArr: [],
          };
        }
      };
      all().then((res) => {
        let dataArr = res.newArr;
        targetNames =
          dataArr
            ?.filter((it) => targetIdList?.indexOf(it.value) > -1)
            ?.map((it) => it.label)
            ?.join(",") || "";
        let params = {
            sendTo,
            targetNames,
            sendProcess,
            sendProcessName:
              sendProcessArr.filter((it) => it.value == sendProcess).length > 0
                ? sendProcessArr.filter((it) => it.value == sendProcess)[0]
                    .label
                : "",
            initialUnit,
            initialTime,
            intervalTime,
            intervalUnit,
            sendNum,
            targetIdList,
            id: iftype.id
              ? iftype.id
              : moment().valueOf() +
                Math.floor(Math.random() * (9999 - 1000)) +
                1000,
            sendToName:
              sendToArr.filter((it) => it.value == sendTo).length > 0
                ? sendToArr.filter((it) => it.value == sendTo)[0].label
                : "",
            initialUnitName:
              unitArr.filter((it) => it.value == initialUnit).length > 0
                ? unitArr.filter((it) => it.value == initialUnit)[0].label
                : "",
            intervalUnitName:
              unitArr.filter((it) => it.value == intervalUnit).length > 0
                ? unitArr.filter((it) => it.value == intervalUnit)[0].label
                : "",
          },
          newTable;
        if (iftype.val == "edit") {
          newTable = tableData.map((it) => {
            if (it.id == iftype.id) {
              it = { ...params };
            }
            return it;
          });
        } else {
          newTable = [...tableData];
          newTable.unshift(params);
        }
        dispatch({ type: "changeTableData", tableData: newTable });
      });
    },
    saveForm = () => {
      let editId = rowMessage ? { id: rowMessage.id } : {},
        all = async () => {
          let values = await forms.validateFields(),
            valuesc = await form.validateFields();
          return {
            values,
            valuesc,
          };
        };
      all().then((res) => {
        if (!tableData.length) {
          return message.warning("基础配置不可为空！");
        }
        let detailList = tableData.map((it) => {
            if (iftypeParent.val == "edit") {
              return {
                sendProcess: it.sendProcess,
                sendTo: it.sendTo,
                targetIdList: it.targetIdList,
                initialTime: it.initialTime,
                initialUnit: it.initialUnit,
                intervalTime: it.intervalTime,
                intervalUnit: it.intervalUnit,
                sendNum: it.sendNum,
                id: it.id && typeof it.id == "number" ? "" : it.id,
              };
            } else {
              return {
                sendProcess: it.sendProcess,
                sendTo: it.sendTo,
                targetIdList: it.targetIdList,
                initialTime: it.initialTime,
                initialUnit: it.initialUnit,
                intervalTime: it.intervalTime,
                intervalUnit: it.intervalUnit,
                sendNum: it.sendNum,
              };
            }
          }),
          params = {
            ...res.values,
            ...res.valuesc,
            detailList,
            ...editId,
          };
        run({
          url: "/ngic-base-business/paBusinessMsgOption/save",
          params: { ...params },
        });
      });
    };

  function showTitleorContent(val) {
    if (val == 4) {
      dispatch({ type: "changeHideTitle", hidesTitle: false });
    } else {
      dispatch({ type: "changeHideTitle", hidesTitle: false });
    }
    if (val == 2) {
      dispatch({ type: "changeHideContent", hidesContent: false });
    } else {
      dispatch({ type: "changeHideContent", hidesContent: false });
    }
  }
  function getdatabase(val) {
    let database;
    switch (val) {
      case 2:
        database = factorySelect;
        break;
      case 3:
        database = zuzhi;
        break;
      case 4:
        database = selectionBoxAll;
        break;
    }
    return database;
  }
  function getformdatabase(val) {
    let database;
    switch (val) {
      case 4:
        database = roleList;
        break;
      case 5:
        database = currentUserList;
        break;
    }
    return database;
  }

  return (
    <div>
      <InitForm
        fields={formFields}
        onChange={(changedValues, allValues) => {
          for (let i in changedValues) {
            if (i == "sendMethodType") {
              showTitleorContent(changedValues[i]);
            }
            if (i == "fitField") {
              let database = getdatabase(changedValues[i]);
              for (let j in formFields) {
                if (j == "fieldId" && changedValues[i] == 1) {
                  formFields[j].hides = true;
                } else if (j == "fieldId" && changedValues[i] != 1) {
                  formFields[j].hides = false;
                  formFields[j].options = {
                    database,
                    params: {},
                  };
                  formFields[j].type =
                    changedValues[i] == 3 ? "treeselect" : "select";

                  forms.setFieldsValue({ fieldId: "" });
                }
              }
              dispatch({ type: "changeFormFields", formFields: formFields });
            }
          }
        }}
        actions={(form, submitBtn) => {
          return null;
        }}
        formRef={forms}
      ></InitForm>
      <Form form={form}>
        {!hidesTitle && (
          <Form.Item
            name="sendTitle"
            rules={[
              {
                required: true,
                message: "请输入推送标题",
              },
            ]}
          >
            <div>
              <div>
                <span style={{ color: "#ff4d4f" }}>*</span> 推送标题
              </div>
              <TextArea
                rows={4}
                defaultValue={
                  iftypeParent.val == "edit" ? rowMessage.sendTitle : ""
                }
              />
            </div>
          </Form.Item>
        )}
        {(!hidesTitle || !hidesContent) && (
          <Button
            type="primary"
            style={{ marginBottom: 15 }}
            onClick={() => {
              let params = forms.getFieldValue("businessMsgSceneId");
              dispatch({ type: "openVariable", variableExtraparams: params });
            }}
          >
            查看变量
          </Button>
        )}
        {!hidesContent && (
          <Form.Item
            name="sendContent"
            rules={[
              {
                required: true,
                message: "请输入推送内容",
              },
            ]}
          >
            <div>
              <div>
                <span style={{ color: "#ff4d4f" }}>*</span> 推送内容
              </div>
              <TextArea
                rows={4}
                defaultValue={
                  iftypeParent.val == "edit" ? rowMessage.sendContent : ""
                }
              />
            </div>
          </Form.Item>
        )}
      </Form>
      {!tableLoading && (
        <AutoTable
          pagetitle="基础设置"
          pageextra={extrarender}
          columns={columns}
          actionRef={actionRef}
          onRef={(node) => (ChildRef = node)}
          dataSource={tableData}
        ></AutoTable>
      )}
      <div style={{ display: "flex", marginTop: 15 }}>
        <Button
          loading={loading}
          type="primary"
          size="large"
          style={{ flex: 1 }}
          onClick={saveForm}
        >
          提交
        </Button>
      </div>
      <Modal
        maskClosable={false}
        title={iftype.title}
        visible={vs}
        onCancel={() => dispatch({ type: "close" })}
        style={{ top: 20 }}
        footer={false}
        width="1000px"
        destroyOnClose={true}
      >
        <InitForm
          fields={tableFields}
          submitData={(values, fn) => {
            saveData(values, fn);
          }}
          formRef={tableFormRef}
          onChange={(changedValues, allValues) => {
            for (let i in changedValues) {
              if (i == "sendTo") {
                for (let j in tableField) {
                  if (j == "targetIdList") {
                    tableFormRef.setFieldsValue({ targetIdList: [] });
                    tableField[j].value = [];
                    if (changedValues[i] != 4 && changedValues[i] != 5) {
                      tableField[j].hides = true;
                    } else {
                      let database = getformdatabase(changedValues[i]);
                      tableField[j].hides = false;
                      tableField[j].options = {
                        database,
                        params: {},
                      };
                    }
                  }
                }
                dispatch({
                  type: "changeTableFields",
                  tableFields: tableField,
                });
              }
            }
          }}
        ></InitForm>
      </Modal>
      <Drawer
        title={"查看变量"}
        closable={true}
        visible={variableVisible}
        onClose={() => dispatch({ type: "close" })}
        destroyOnClose={true}
        afterVisibleChange={(v) => {
          dispatch({ type: "changeShown", shown: v });
        }}
        width="40%"
      >
        {shown && (
          <Variable
            businessMsgSceneId={variableExtraparams}
            dispatch={dispatch}
          />
        )}
      </Drawer>
    </div>
  );
};

export default Formpage;
