import { Cell } from "@antv/x6";
import { Select, Form, Input, Divider, AutoComplete } from "antd";
import { useEffect, useState } from "react";
import {
  ListLangBySearchKey,
  GetAllPage,
  GetAllTablesAndViews,
  GetAllWfScene,
  GetAllWorkflows,
} from "@/api";
import { useRequest } from "umi";
import SelectModal from "./SelectModal";
import { CorrelationType } from "@/enum";

interface LanItem {
  en: string;
  key: string;
  ["zh-CN"]: string;
}
export default function NodeAttrs({
  cell,
  onChange,
}: {
  cell?: Cell;
  onChange?: (data: any) => void;
}) {
  const defaultModel = {
    "zh-CN": "",
    en: "",
    langText: "",
    desc: "",
    linkType: CorrelationType.scene,
    linkValue: {
      value: undefined,
      label: undefined,
    },
    remember: "",
    recordTime: "",
    recordUser: "",
    recordConent: "",
  };

  const [lanOptions, setLanOptions] = useState<any[]>([]);
  const [formModel, setFormModel] = useState(cell?.data?.attrs || defaultModel);

  useEffect(() => {
    if(cell) {
      setFormModel(cell?.data?.attrs || defaultModel);
    }
  }, [cell]);

  const { run } = useRequest(ListLangBySearchKey, {
    manual: true,
    onSuccess(data, params) {
      setLanOptions(
        (data.result || []).map((item: LanItem) => ({
          ...item,
          label: `${item.en || ""}[zh-CN:${item["zh-CN"]}]`,
          value: item[params[0].searchLan],
        }))
      );
    },
  });

  useEffect(() => {
    onChange?.(formModel);
  }, [formModel]);

  const handleSearch = (serchKey: string, searchLan: "en" | "zh-CN") => {
    run({
      maxCount: 10,
      searchKey: serchKey,
      searchLan,
    });
  };

  const handleChange = (key: string, value: any) => {
    setFormModel({
      ...formModel,
      langText: "",
      [key]: value,
    });
  };

  const handleSelectLang = (option: LanItem) => {
    setFormModel(() => {
      return {
        ...formModel,
        langText: option.key,
        en: option?.en,
        ["zh-CN"]: option?.["zh-CN"],
      };
    });
  };

  return (
    <div>
      <Divider style={{ margin: "0" }}>基本</Divider>
      <section className="px-16px">
        <Form.Item
          label="中文"
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
          layout="vertical"
        >
          <AutoComplete
            allowClear
            placeholder="请输入"
            options={lanOptions}
            onSearch={(val) => handleSearch(val, "zh-CN")}
            value={formModel["zh-CN"]}
            onChange={(val) => handleChange("zh-CN", val)}
            onSelect={(_val, opt) => handleSelectLang(opt)}
            disabled={!cell}
          />
        </Form.Item>
        <Form.Item
          label="English"
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
          layout="vertical"
        >
          <AutoComplete
            allowClear
            style={{ width: "100%" }}
            placeholder="请输入"
            options={lanOptions}
            onSearch={(val) => handleSearch(val, "en")}
            value={formModel.en}
            onChange={(val) => handleChange("en", val)}
            onSelect={(_val, opt) => handleSelectLang(opt)}
            disabled={!cell}
          />
        </Form.Item>
        <Form.Item
          label="节点描述"
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
        >
          <Input.TextArea
            placeholder="请输入"
            value={formModel.desc}
            onChange={(e) => handleChange("desc", e.target.value)}
            disabled={!cell}
          />
        </Form.Item>
        <Form.Item
          label="关联类型"
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
        >
          <Select
            placeholder="请选择"
            disabled={!cell}
            options={[
              { value: CorrelationType.scene, label: "场景" },
              { value: CorrelationType.flow, label: "流程" },
              { value: CorrelationType.page, label: "页面" },
              { value: CorrelationType.table, label: "数据表" },
              { value: CorrelationType.view, label: "视图" },
            ]}
            value={formModel.linkType}
            onChange={(val) => {
              setFormModel({
                ...formModel,
                linkType: val,
                linkValue: {
                  label: undefined,
                  value: undefined,
                },
              });
            }}
          />
        </Form.Item>
        <Form.Item
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
        >
          {formModel.linkType === CorrelationType.scene && (
            <SelectModal
              key="1"
              value={formModel.linkValue}
              api={GetAllWfScene}
              disabled={!cell}
              onSuccess={(data) => {
                return data?.result?.model || [];
              }}
              columns={[
                { title: "名称", dataIndex: "name" },
                { title: "描述", dataIndex: "memo" },
              ]}
              onChange={(rows) => {
                const item = rows[0];
                item &&
                  handleChange("linkValue", {
                    value: item.id,
                    label: item.name,
                  });
              }}
              defaultParams={[
                {
                  currentPage: 1,
                  pageSize: 10,
                  orderByProperty: "Id",
                  Ascending: false,
                  filters: [
                    {
                      name: "EnterpriseId",
                    },
                  ],
                },
              ]}
            />
          )}
          {formModel.linkType === CorrelationType.flow && (
            <SelectModal
              key="2"
              value={formModel.linkValue}
              api={GetAllWorkflows}
              disabled={!cell}
              onSuccess={(data) => {
                return data?.result || [];
              }}
              columns={[
                { title: "名称", dataIndex: "name" },
                { title: "描述", dataIndex: "memo" },
              ]}
              onChange={(rows) => {
                const item = rows[0];
                item &&
                  handleChange("linkValue", {
                    value: item.id,
                    label: item.name,
                  });
              }}
              defaultParams={[
                {
                  currentPage: 1,
                  pageSize: 10,
                  orderByProperty: "Id",
                  Ascending: false,
                  filters: [
                    {
                      name: "EnterpriseId",
                    },
                  ],
                },
              ]}
            />
          )}
          {formModel.linkType === CorrelationType.page && (
            <SelectModal
              key="3"
              value={formModel.linkValue}
              api={GetAllPage}
              disabled={!cell}
              onSuccess={(data) => {
                return data?.result || [];
              }}
              columns={[
                {
                  title: "名称",
                  dataIndex: "name",
                  render: (_val, record) => (
                    <span>
                      {record.name}({record.fileName})
                    </span>
                  ),
                },
                { title: "描述", dataIndex: "description" },
              ]}
              onChange={(rows) => {
                const item = rows[0];
                item &&
                  handleChange("linkValue", {
                    value: item.id,
                    label: item.name,
                  });
              }}
            />
          )}
          {formModel.linkType === CorrelationType.table && (
            <SelectModal
              key="4"
              value={formModel.linkValue}
              api={GetAllTablesAndViews}
              disabled={!cell}
              onSuccess={(data) => {
                return data?.result?.appBusinessTables || [];
              }}
              columns={[
                {
                  title: "名称",
                  dataIndex: "name",
                  render: (val, record) => (
                    <span>
                      {record.name}({record.schemaName})
                    </span>
                  ),
                },
                { title: "描述", dataIndex: "description" },
              ]}
              onChange={(rows) => {
                const item = rows[0];
                item &&
                  handleChange("linkValue", {
                    value: item.id,
                    label: item.name,
                  });
              }}
            />
          )}
          {formModel.linkType === CorrelationType.view && (
            <SelectModal
              key="5"
              value={formModel.linkValue}
              api={GetAllTablesAndViews}
              disabled={!cell}
              onSuccess={(data) => {
                return data?.result?.bpmViewTables || [];
              }}
              columns={[
                {
                  title: "名称",
                  dataIndex: "name",
                  render: (val, record) => (
                    <span>
                      {record.name}({record.schemaName})
                    </span>
                  ),
                },
                { title: "描述", dataIndex: "description" },
              ]}
              onChange={(rows) => {
                const item = rows[0];
                item &&
                  handleChange("linkValue", {
                    value: item.id,
                    label: item.name,
                  });
              }}
            />
          )}
        </Form.Item>
      </section>
      <Divider style={{ margin: "0" }}>需求</Divider>
      <section className="px-16px">
        <Form.Item
          label="参与人"
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
        >
          <Input
            placeholder="请输入"
            value={formModel.remember}
            onChange={(e) => handleChange("remember", e.target.value)}
            disabled={!cell}
          />
        </Form.Item>
        <Form.Item
          label="记录时间"
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
        >
          <Input
            placeholder="请输入"
            value={formModel.recordTime}
            onChange={(e) => handleChange("recordTime", e.target.value)}
            disabled={!cell}
          />
        </Form.Item>
        <Form.Item
          label="记录人"
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
        >
          <Input.TextArea
            placeholder="请输入"
            value={formModel.recordUser}
            onChange={(e) => handleChange("recordUser", e.target.value)}
            disabled={!cell}
          />
        </Form.Item>
        <Form.Item
          label="内容"
          labelCol={{ span: 10 }}
          labelAlign="left"
          className="mb-8px"
          colon={false}
        >
          <Input.TextArea
            rows={5}
            placeholder="请输入"
            value={formModel.recordConent}
            onChange={(e) => handleChange("recordConent", e.target.value)}
            disabled={!cell}
          />
        </Form.Item>
      </section>
    </div>
  );
}
