import React, { useState, useRef, useReducer } from "react";
import {
  Modal,
  Button,
  Drawer,
  Tooltip,
  Popconfirm,
  message,
  Switch,
} from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import InitForm from "@/components/InitForm";
import { useRequest } from "umi";
import defaultFields from "./fields";
import { doFetch } from "@/utils/doFetch";
import { deviceprovideDetail, deleteProvideCheck } from "@/services/device";
import { deviceprovideDetails } from "@/utils/detailTotalCard";
import Details from "@/components/Details";
import { useAsyncEffect } from "ahooks";
import tempfields from "@/utils/tempfields";

const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  details: {
    dataSource: {},
    totalCard: [],
  },
  visible: 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 "edit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "编辑供应商",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
      };
      break;
    case "cdetails":
      let n = 1,
        dataSource = action.dataSource;
      let special = action?.dataSource?.supplierCharList?.map?.((it) => {
        n++;
        let key = n.toString();
        dataSource[key] = it?.fieldRealValue;
        return {
          title: it?.fieldName,
          key: key,
        };
      });
      let extraspecial = [
        {
          cardTitle: "特殊属性",
          itemData: special,
        },
      ];

      newState = {
        ...state,
        details: {
          dataSource: action.dataSource,
          totalCard: [...deviceprovideDetails, ...extraspecial],
        },
        visible: true,
      };
      break;
    case "close":
      newState = {
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        details: {
          dataSource: {},
          totalCard: [],
        },
        visible: false,
      };
      break;
  }
  return newState;
}

const Deviceprovide = (props) => {
  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const [state, dispatch] = useReducer(reducer, initState),
    { vs, fields, iftype, details, visible } = state,
    columns = [
      {
        title: "供应商编号",
        dataIndex: "supplierNo",
        key: "supplierNo",
      },
      {
        title: "供应商名称",
        dataIndex: "supplierName",
        key: "supplierName",
        render: (_, row) => {
          return (
            <div
              style={{
                padding: "3px 0",
                overflow: "hidden",
                whiteSpace: "nowrap",
                textOverflow: "ellipsis",
              }}
            >
              <Tooltip title={row.supplierName}>
                <a
                  onClick={() => {
                    deviceprovideDetail({ id: row.id }).then((res) => {
                      let data = res?.data?.data || {};
                      dispatch({ type: "cdetails", dataSource: data });
                    });
                  }}
                >
                  {row.supplierName}
                </a>
              </Tooltip>
            </div>
          );
        },
      },
      {
        title: "联系电话",
        dataIndex: "telephone",
        key: "telephone",
      },
      {
        title: "邮箱",
        dataIndex: "email",
        key: "email",
      },
      {
        title: "地址",
        dataIndex: "address",
        key: "address",
        search: false,
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark",
        search: false,
      },
      {
        title: "评分",
        dataIndex: "score",
        key: "score",
        render: (_, row) => {
          return <div>{row.score}星</div>;
        },
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        valueType: "select",
        options: [
          {
            label: "启用",
            value: 1,
          },
          {
            label: "关闭",
            value: 0,
          },
        ],
        render: (text, row, _, action) => {
          return (
            <Popconfirm
              title="是否开启或关闭供应商?"
              onConfirm={() => {
                run({
                  url: "/ngic-auth/sysSupplier/update/status",
                  params: { id: row.id, status: row.status == 1 ? 0 : 1 },
                });
              }}
              onCancel={() => {}}
              okText="确定"
              cancelText="取消"
              disabled={
                !getPrem("equipmentSupplier_updatestatus", "ifs") ||
                row.sourceType == 1
              }
            >
              <Switch
                checked={row.status == 1 ? true : false}
                checkedChildren="开启"
                unCheckedChildren="关闭"
                defaultChecked={false}
              />
            </Popconfirm>
          );
        },
      },
      {
        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") {
          message.success("操作成功！");
          reload();
          dispatch({ type: "close" });
        }
      },
    });
  const [extrafields, setextrafields] = useState({});
  const [subdata, setsubdata] = useState([]);
  const [curitem, setcuritem] = useState({});
  function extraAction(text, record, _, action) {
    return [
      getPrem("equipmentSupplier_save", action, "修改", async () => {
        await setcuritem({
          ...record,
          key: "edit",
        });
      }),
      record.sourceType != 1 &&
        getPrem("equipmentSupplier_deleteById", action, "删除", null, {
          title: "确认删除该供应商？",
          onConfirm: () => {
            run({
              url: "/ngic-auth/sysSupplier/deleteById",
              params: { id: record.id },
            });
          },
        }),
    ];
  }
  let saveData = (values, fn) => {
    let newfields = JSON.parse(JSON.stringify(values));
    //新增&修改
    let difrid = iftype.val == "edit" ? { id: curitem.id } : {};
    let supplierUserList = newfields?.supplierUserList?.map((it) => {
      delete it.id;
      return it;
    });
    let supplierCharList = subdata.map((it, i) => {
      let key = "field" + i.toString();
      it.fieldRealValue = values[key];
      delete newfields[key];
      return it;
    });
    let params = {
      ...newfields,
      supplierUserList,
      supplierCharList,
    };
    run({
      url: "/ngic-auth/sysSupplier/save",
      params: { ...params, ...difrid },
    });
  };
  let extrarender = [
    <Button
      disabled={!getPrem("equipmentSupplier_save", "ifs")}
      type="primary"
      onClick={async () => {
        console.log(subdata);
        let result = await tempfields(
          "/ngic-auth/sysSupplierChar/queryCommonList",
          {}
        );
        setsubdata(result?.data);
        for (let i in defaultFields) {
          defaultFields[i].value = null;
          defaultFields[i].disabled = false;
          if (i == "supplierUserList") {
            defaultFields[i].value = [];
          }
          if (i == "status") {
            defaultFields[i].value = 1;
          }
        }
        for (let i in extrafields) {
          extrafields[i].value = null;
          if (extrafields[i]["multiple"] == true) {
            extrafields[i].value = [];
          }
        }
        dispatch({
          type: "add",
          fields: { ...defaultFields, ...result?.fields },
        });
      }}
    >
      新增
    </Button>,
  ];

  useAsyncEffect(async () => {
    let result = await tempfields(
      "/ngic-auth/sysSupplierChar/queryCommonList",
      { id: curitem.id }
    );
    await setextrafields(result?.fields);
    await setsubdata(result?.data);
    if (curitem.key == "edit") {
      doFetch({
        url: "/ngic-auth/sysSupplier/query/detail",
        params: { id: curitem.id },
      }).then((res) => {
        if (res.code == "0000") {
          let data = res?.data?.data || {};
          for (let i in defaultFields) {
            defaultFields[i].value = data[i];
            if (i == "status" && curitem.sourceType == 1) {
              defaultFields[i].disabled = true;
            } else {
              defaultFields[i].disabled = false;
            }
          }
          dispatch({
            type: "edit",
            fields: { ...defaultFields, ...result?.fields },
          });
        }
      });
    }
  }, [curitem]);

  return (
    <div>
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        path="/ngic-auth/sysSupplier/queryList"
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
      ></AutoTable>

      <Modal
        maskClosable={false}
        title={iftype.title}
        visible={vs}
        onCancel={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={1000}
      >
        <InitForm
          fields={fields}
          submitData={(values) => {
            saveData(values);
          }}
          onChange={(changedValues, allValues) => {
            //联动操作
          }}
          submitting={loading || !vs}
        ></InitForm>
      </Modal>
      <Details
        title="供应商详情"
        closable={true}
        visible={visible}
        onClose={() => dispatch({ type: "close" })}
        destroyOnClose={true}
        afterVisibleChange={(v) => {}}
        width="100%"
        className="drawerDetails"
        {...details}
      ></Details>
    </div>
  );
};
export default Deviceprovide;
