import { FC, useEffect, useMemo, useState } from "react";
import { Button, Form, Input, Select, Table } from "antd";
import { useNavigate, useParams } from "react-router-dom";
import { getManageNormListApi } from "@/api";
import { debounce } from "lodash";
import {
  IManageFormDetail,
  IManageIndexDetail,
  IManageNormItem,
  YES_OR_NO,
} from "@/types";
import { SelfReportScoreModal } from "../SelfReportScoreModal";
import { ColumnsType } from "antd/es/table";
import { IndexDetailModal } from "../IndexDetailModal";

export interface IndexAssessmentProps {
  detail: IManageIndexDetail | IManageFormDetail | null;
  isReportDetail?: boolean;
  isEvalutionDetail?: boolean;
}

const DEFAULT_PARAMS = {
  searchKey: "",
  uploadStatus: undefined,
};

const CONFIRM_OPTIONS = [
  {
    label: "全部",
    value: "",
  },
  {
    label: "已完成",
    value: YES_OR_NO.YES,
  },
  {
    label: "未完成",
    value: YES_OR_NO.NO,
  },
];

export const IndexAssessment: FC<IndexAssessmentProps> = ({
  detail,
  isReportDetail,
  isEvalutionDetail,
}) => {
  const navigate = useNavigate();
  const routeParams = useParams();
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState<any>({
    ...DEFAULT_PARAMS,
  });
  const [list, setList] = useState<IManageNormItem[]>([]);
  const [checkedItem, setCheckedItem] = useState<null | IManageNormItem>(null);
  const [selfReportVisible, setSelfReportVisible] = useState(false);
  const [indexDetailVisible, setIndexDetailVisible] = useState(false);
  const columns = useMemo(() => {
    const stack: ColumnsType<IManageNormItem> = [
      {
        title: "序号",
        align: "center",
        minWidth: 80,
        render: (val, record, index) => index + 1,
      },
      {
        title: "标题",
        dataIndex: "name",
        align: "center",
        minWidth: 200,
      },
      {
        title: "说明",
        minWidth: 300,
        align: "center",
        render: (val) =>
          val.remark ? (
            <p className="limit-line line-2">{val.remark}</p>
          ) : (
            <p className="empty-text">（空）</p>
          ),
      },
      {
        title: "分值",
        align: "center",
        minWidth: 100,
        render: (val) => val.score || <p className="empty-text">（空）</p>,
      },
      {
        title: "资料上传 ",
        minWidth: 120,
        align: "center",
        render: (val) => (
          <Button
            type="link"
            onClick={() => {
              setCheckedItem(val);
              setIndexDetailVisible(true);
            }}
          >
            查看
          </Button>
        ),
      },
      {
        title: "上传状态",
        align: "center",
        minWidth: 120,
        render: (val) => <p className="empty-text">（空）</p>,
      },
      {
        title: "打分点",
        align: "center",
        minWidth: 100,
        render: (val) => (val.isPoint === YES_OR_NO.YES ? "是" : "否"),
      },
      {
        title: "责任部门",
        align: "center",
        minWidth: 120,
        dataIndex: "deptName",
      },
      {
        title: "评定得分",
        align: "center",
        minWidth: 120,
        render: (val) => val.score || <p className="empty-text">（空）</p>,
      },
      {
        title: "评定人",
        align: "center",
        minWidth: 100,
        render: (val) => <p className="empty-text">（空）</p>,
      },
      {
        title: "评定意见",
        align: "center",
        minWidth: 120,
        render: (val) => <p className="empty-text">（空）</p>,
      },
      {
        title: "操作",
        align: "center",
        hidden: !isEvalutionDetail,
        render: () => (
          <Button
            type="link"
            onClick={() => navigate("/management/evaluation/detail/submit")}
          >
            评定
          </Button>
        ),
      },
    ];

    if (
      isReportDetail &&
      (detail as IManageFormDetail)?.isSelf === YES_OR_NO.YES
    ) {
      stack.splice(
        7,
        0,
        {
          title: "自评得分",
          align: "center",
          minWidth: 120,
          render: (val) =>
            !val.selfScore ? (
              <Button
                type="text"
                color="primary"
                variant="link"
                onClick={() => {
                  setCheckedItem(val);
                  setSelfReportVisible(true);
                }}
              >
                (空)
              </Button>
            ) : (
              val.selfScore
            ),
        },
        {
          title: "自评人",
          align: "center",
          minWidth: 100,
          render: (val) => val.selfName || <p className="empty-text">（空）</p>,
        }
      );
    }

    return stack;
  }, [detail]);

  const getList = async () => {
    try {
      setLoading(true);
      const data = await getManageNormListApi({
        deptId: routeParams.id as string,
        ...params,
      });
      setList(data);
    } finally {
      setLoading(false);
    }
  };

  const debounceSearch = useMemo(
    () =>
      debounce((changedVal: unknown, vals: any) => {
        setParams({ ...params, ...vals });
      }, 500),
    [params]
  );

  const handleSelfScoreCancel = () => {
    setCheckedItem(null);
    setSelfReportVisible(false);
  };

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

  return (
    <>
      <Form layout="inline" onValuesChange={debounceSearch}>
        <Form.Item label="搜索" name="searchKey">
          <Input allowClear className="w220" placeholder="请输入指标名称" />
        </Form.Item>
        <Form.Item label="上传状态">
          <div className="w160">
            <Form.Item noStyle name="uploadStatus">
              <Select
                allowClear
                options={CONFIRM_OPTIONS}
                placeholder="请选择"
              />
            </Form.Item>
          </div>
        </Form.Item>
        {/* <Form.Item label="责任部门">
          <div className="w160">
            <Select placeholder="请选择" />
          </div>
        </Form.Item> */}
        <Form.Item>
          <Button type="primary" onClick={getList}>
            查询
          </Button>
        </Form.Item>
      </Form>

      <div style={{ margin: "20px -25px" }}>
        <Table
          className="cus-table"
          rowKey="id"
          scroll={{
            x: true,
          }}
          loading={loading}
          dataSource={list}
          columns={columns}
        />
      </div>

      <IndexDetailModal
        open={indexDetailVisible}
        id={checkedItem?.normId || 0}
        title={checkedItem?.name || ""}
        onCancel={() => {
          setCheckedItem(null);
          setIndexDetailVisible(false);
        }}
      />

      <SelfReportScoreModal
        open={selfReportVisible}
        item={checkedItem}
        onOk={() => {
          getList();
          handleSelfScoreCancel();
        }}
        onCancel={handleSelfScoreCancel}
      />
    </>
  );
};
