import { FC, useEffect, useRef, useState } from "react";
import { Button, Form, InputNumber, Space, Table } from "antd";
import { useParams } from "react-router-dom";
import { ActionType, EditableProTable } from "@ant-design/pro-components";
import { PlusOutlined } from "@ant-design/icons";
import {
  AddIndexModal,
  AddIndexTemplateModal,
  PageContainer,
  Search,
} from "@/components";
// import { uniq, uniqBy } from "lodash";
import { ASS_INDEX_TYPE } from "@/types";
import style from "./index.module.scss";
import {
  getManageAssFixedListApi,
  getManageAssOperationListApi,
  saveManageAssOperationWeightApi,
  setManageAssFixedApi,
  setManageAssOperationApi,
} from "@/api";
import { DageLoading } from "@dage/pc-components";

const SettingIndexPage: FC = () => {
  const params = useParams();
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  // const tableRef = useRef<EditableFormInstance<TableIndexType>>();
  const [keyword, setKeyword] = useState("");
  const [indexModalVisible, setIndexModalVisible] = useState(false);
  const [indexTemplateModalVisible, setIndexTemplateModalVisible] =
    useState(false);
  const [loading, setLoading] = useState(false);
  // 设置定级指标
  const isFixed = params.type === ASS_INDEX_TYPE.FIXED;
  // 总分值
  const [score, setScore] = useState(0);
  const [museumScoreList, setMuseumScoreList] = useState<any[]>([]);

  const getList = async (searchKey?: string) => {
    try {
      setLoading(true);

      if (isFixed) {
        const data = await getManageAssFixedListApi(params.id!, searchKey);
        form.setFieldValue("list", data);

        if (!searchKey)
          setScore(data.reduce((acc, currentVal) => acc + currentVal.score, 0));
      } else {
        const data = await getManageAssOperationListApi(params.id!, searchKey);
        setMuseumScoreList([
          {
            id: 1,
            ...data.gist,
          },
        ]);
        form.setFieldValue("list", data.list);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleAddIndexItem = async (keys: string[]) => {
    if (isFixed) {
      await setManageAssFixedApi(params.id!, keys);
    } else {
      await setManageAssOperationApi(params.id!, keys);
    }
    getList();
  };
  // const handleAddIndexItem = async (
  //   keys: Key[],
  //   rows: AssIndexTreeItemType[]
  // ) => {
  //   form.setFieldValue(
  //     "list",
  //     uniqBy([...(form.getFieldValue("list") || []), ...rows], "id")
  //   );
  //   setEditableKeys(uniq([...editableKeys, ...keys]));
  // };

  const handleSearch = () => {
    getList(keyword);
  };

  const handleReset = () => {
    setKeyword("");
    getList("");
  };

  useEffect(() => {
    getList();
  }, []);

  return (
    <PageContainer title="设置指标">
      <Form
        labelCol={{ span: 4, offset: 3 }}
        form={form}
        size="large"
        className={style.settingForm}
      >
        <Form.Item label="指标总分值">
          <Button type="primary" onClick={() => getList()}>
            计算
          </Button>

          {isFixed ? (
            <span style={{ paddingLeft: 15 }}>{score}分</span>
          ) : (
            <Table
              style={{ marginTop: 20 }}
              rowKey="id"
              dataSource={museumScoreList}
              columns={[
                {
                  title: "一级博物馆",
                  dataIndex: "one",
                  align: "center",
                },
                {
                  title: "二级博物馆",
                  dataIndex: "two",
                  align: "center",
                },
                {
                  title: "三级博物馆",
                  dataIndex: "three",
                  align: "center",
                },
              ]}
            />
          )}
        </Form.Item>
        <Form.Item required label="考核指标">
          <Form.Item noStyle name="list">
            <EditableProTable
              className="custom-pro-table mw650"
              actionRef={actionRef}
              // editableFormRef={tableRef}
              rowKey="id"
              style={{ marginTop: -15 }}
              recordCreatorProps={false}
              columns={
                isFixed
                  ? [
                      {
                        title: "指标级别",
                        dataIndex: "level",
                        align: "center",
                        editable: false,
                      },
                      {
                        title: "指标名称",
                        dataIndex: "name",
                        align: "center",
                        editable: false,
                      },
                      {
                        title: "填报方式",
                        dataIndex: "fill",
                        align: "center",
                        width: "230px",
                        // renderFormItem: () => (
                        //   <Radio.Group>
                        //     <Radio value="point">手动填报</Radio>
                        //     <Radio value="api">
                        //       API{" "}
                        //       <Tooltip title="以 type，start_date，end_date请求API数据。当API获取数据失败时，将自动转为手动填报">
                        //         <Tag bordered={false} color="warning">
                        //           注
                        //         </Tag>
                        //       </Tooltip>
                        //     </Radio>
                        //   </Radio.Group>
                        // ),
                      },
                      {
                        title: "分值",
                        dataIndex: "score",
                        align: "center",
                        width: "130px",
                      },
                    ]
                  : [
                      {
                        title: "指标级别",
                        dataIndex: "level",
                        align: "center",
                        editable: false,
                      },
                      {
                        title: "指标名称",
                        dataIndex: "name",
                        align: "center",
                        editable: false,
                      },
                      {
                        title: "指标权重",
                        dataIndex: "weight",
                        align: "center",
                        width: "130px",
                        render: (_, row) =>
                          row.weight <= 0 ? "/" : row.weight,
                        formItemProps: () => {
                          return {
                            rules: [
                              { required: true, message: "此项为必填项" },
                            ],
                          };
                        },
                        renderFormItem: () => (
                          <InputNumber
                            variant="borderless"
                            size="small"
                            min={1}
                            max={100}
                            controls={false}
                            precision={0}
                            placeholder="请输入1~100的数字"
                            className="w100"
                            addonAfter="%"
                          />
                        ),
                      },
                      {
                        title: "操作",
                        valueType: "option",
                        render: (_, row) => [
                          <a
                            key="edit"
                            onClick={() => {
                              actionRef.current?.startEditable(row.id);
                            }}
                          >
                            编辑
                          </a>,
                        ],
                      },
                    ]
              }
              headerTitle={
                <Space>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    style={{ background: "var(--second-color)" }}
                    onClick={() => setIndexModalVisible(true)}
                  >
                    新建指标
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => setIndexTemplateModalVisible(true)}
                  >
                    从模板中添加
                  </Button>
                </Space>
              }
              toolBarRender={() => [
                <Search
                  value={keyword}
                  placeholder="请输入要搜索的指标名称"
                  style={{ maxWidth: 335 }}
                  onChange={(v) => setKeyword(v.target.value)}
                  onSearch={handleSearch}
                  onReset={handleReset}
                />,
              ]}
              editable={{
                type: "multiple",
                actionRender: (row, config, defaultDoms) => {
                  return [defaultDoms.save, defaultDoms.cancel];
                },
                onSave: async (id, row) => {
                  await saveManageAssOperationWeightApi(row.id, row.weight);
                },
              }}
            />
          </Form.Item>
        </Form.Item>
      </Form>

      <AddIndexModal
        open={indexModalVisible}
        onOk={handleAddIndexItem}
        onCancel={() => setIndexModalVisible(false)}
      />
      <AddIndexTemplateModal
        open={indexTemplateModalVisible}
        onOk={handleAddIndexItem}
        onCancel={() => setIndexTemplateModalVisible(false)}
      />

      {loading && <DageLoading />}
    </PageContainer>
  );
};

export default SettingIndexPage;
