import React, { memo, useEffect, useRef, useState, useReducer } from "react";
import {
  Image,
  Divider,
  Menu,
  Dropdown,
  Button,
  Modal,
  Row,
  Col,
  Tooltip,
  Drawer,
} from "antd";
import { connect, useRequest } from "umi";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import { doFetch } from "@/utils/doFetch";
import { paBusinessMsgScene, paBusinessMsgOption } from "@/services/platform";
import { addFields } from "./fields";
import Formpage from "./Formpage";
import Details from "@/components/Details";
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  details: {
    totalTitle: "",
    visible: false,
    dataSource: {},
    totalCard: [],
  },
  shown: false,
  rowMessage: {},
};

function reducer(state, action) {
  if (action.type == "add") {
    return {
      ...state,
      vs: true,
      fields: action.fields,
      iftype: {
        val: "add",
        title: "新增推送配置",
      },
      rowMessage: {},
    };
  } else if (action.type == "close") {
    return {
      ...state,
      vs: false,
      iftype: {},
      fields: {},
      details: {
        totalTitle: "",
        visible: false,
        dataSource: {},
        totalCard: [],
      },
      shown: false,
    };
  } else if (action.type == "edit") {
    return {
      ...state,
      vs: true,
      fields: action.fields,
      iftype: {
        val: "edit",
        title: "修改推送配置",
        id: action.rowMessage.id,
      },
      rowMessage: action.rowMessage,
    };
  } else if (action.type == "seeDetails") {
    return {
      ...state,
      details: {
        totalTitle: "推送详情",
        visible: true,
        dataSource: { ...action.dataSource },
        totalCard: [...action.totalCard],
      },
    };
  } else if (action.type == "changeShown") {
    return {
      ...state,
      shown: action.shown,
    };
  }
}

const Pushdeploy = (props) => {
  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const [state, dispatch] = useReducer(reducer, initState),
    { vs, fields, iftype, details, shown, rowMessage } = state,
    columns = [
      {
        title: "推送类型",
        dataIndex: "msgSceneName",
        key: "businessMsgSceneId",
        valueType: "select",
        render: (_, row) => {
          return (
            <div
              style={{
                padding: "3px 0",
                overflow: "hidden",
                whiteSpace: "nowrap",
                textOverflow: "ellipsis",
              }}
            >
              <Tooltip title={row.msgSceneName}>
                <a
                  onClick={() => {
                    let commons = [
                        {
                          title: "推送类型",
                          key: "msgSceneName",
                        },
                        {
                          title: "推送方式",
                          key: "sendMethodName",
                        },
                        {
                          title: "适用类型",
                          key: "fitFieldName",
                        },
                      ],
                      table = {
                        key: "detailList",
                        col: { span: 24 },
                        type: "table",
                        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,
                          },
                        ],
                      },
                      totalCardsc,
                      contentMsg,
                      fieldMsg;
                    contentMsg = {
                      title: "推送内容",
                      key: "sendContent",
                      col: { span: 24 },
                    };
                    if (row.fitField == 1) {
                      fieldMsg = null;
                    } else {
                      fieldMsg = {
                        title: "类型名称",
                        key: "fieldName",
                      };
                    }
                    totalCardsc = [
                      {
                        cardTitle: "推送信息",
                        itemData: [
                          ...commons,
                          fieldMsg && { ...fieldMsg },
                          contentMsg && { ...contentMsg },
                        ],
                      },
                      {
                        cardTitle: "基础配置",
                        itemData: [{ ...table }],
                      },
                    ];
                    totalCardsc.map((it) => {
                      let newData = it.itemData.filter((item) => item);
                      it.itemData = [...newData];
                    });
                    paBusinessMsgOption({ id: row.id }).then((res) => {
                      if (res.code == "0000") {
                        let data = res?.data?.data || {};
                        dispatch({
                          type: "seeDetails",
                          totalCard: [...totalCardsc],
                          dataSource: { ...data },
                        });
                      }
                    });
                  }}
                >
                  {row.msgSceneName}
                </a>
              </Tooltip>
            </div>
          );
        },
        options: {
          database: paBusinessMsgScene,
          params: {},
        },
      },
      {
        title: "推送方式",
        dataIndex: "sendMethodName",
        key: "sendMethodName",
        search: false,
      },
      {
        title: "适用范围",
        dataIndex: "fitFieldName",
        key: "fitField",
        valueType: "select",
        options: [
          {
            label: "全部",
            value: 1,
          },
          {
            label: "工厂",
            value: 2,
          },
          {
            label: "组织",
            value: 3,
          },
          {
            label: "仓库",
            value: 4,
          },
        ],
      },
      {
        title: "范围名称",
        dataIndex: "fieldName",
        key: "fieldName",
      },
      {
        title: "推送内容",
        dataIndex: "sendContent",
        key: "sendContent",
        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") {
          reload();
          dispatch({ type: "close" });
        }
      },
    });
  function extraAction(text, record, _, action) {
    return (
      <div>
        {getPrem("paBusinessMsgOption_save", action, "修改", () => {
          paBusinessMsgOption({ id: record.id }).then((res) => {
            if (res.code == "0000") {
              let data = res?.data?.data || {};
              for (let i in addFields) {
                addFields[i].value = data[i];
              }
              dispatch({ type: "edit", rowMessage: data, fields: addFields });
            }
          });
        })}
        {getPrem("paBusinessMsgOption_save", "ifs") && (
          <Divider type="vertical" />
        )}
        {getPrem("paBusinessMsgOption_deleteById", action, "删除", null, {
          title: "确认删除该推送配置？",
          onConfirm: () => {
            run({
              url: "/ngic-base-business/paBusinessMsgOption/deleteById",
              params: { id: record.id },
            });
          },
        })}
      </div>
    );
  }
  function reset() {
    reload();
    dispatch({ type: "close" });
  }
  let extrarender = [
    <Button
      disabled={!getPrem("paBusinessMsgOption_save", "ifs")}
      size={"middle"}
      type="primary"
      onClick={() => {
        for (let i in addFields) {
          addFields[i].value = null;
        }
        dispatch({ type: "add", fields: addFields });
      }}
    >
      新增
    </Button>,
  ];
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name}
        pageextra={extrarender}
        columns={columns}
        bordered={false}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/ngic-base-business/paBusinessMsgOption/queryList"
      ></AutoTable>
      <Drawer
        title={iftype.title}
        closable={true}
        visible={vs}
        onClose={() => dispatch({ type: "close" })}
        destroyOnClose={true}
        getContainer={false}
        afterVisibleChange={(v) => {
          dispatch({ type: "changeShown", shown: v });
        }}
        style={{ position: "absolute" }}
        width="100%"
      >
        {shown && (
          <Formpage
            fields={fields}
            rowMessage={rowMessage}
            reset={reset}
            iftypeParent={iftype}
          />
        )}
      </Drawer>
      <Details
        {...details}
        title={details.totalTitle}
        onClose={() => dispatch({ type: "close" })}
        getContainer={false}
        style={{ position: "absolute" }}
        width={800}    
      ></Details>

     
    </div>
  );
};
export default Pushdeploy;
