import React, { useEffect, useRef, useState } from "react";
import { Table, Row, Input, Modal, Button, message } from "antd";
import { useStore } from "../../../store";
import * as API from "../../../api";
import AdviserTaskEdit from "./AdviserTaskEdit";
import { history, useRequest } from "umi";
import { cloneDeep } from "lodash";
import { ColumnsType } from "antd/es/table";

interface AdviserTaskEditForm {
  submit: (callback: (data: any) => void) => void;
}

interface AdviserTaskProps {
  form: any;
}

export default function AdviserTask({ form }: AdviserTaskProps) {
  const adviserTaskEditRef = useRef<AdviserTaskEditForm>(null);
  const {
    shopTaskItem,
    isReadOnly,
    setShopTaskItem,
    editAdviser,
    setEditAdviser,
  } = useStore();
  const [advisersFiltered, setAdvisersFiltered] = useState<API.StaffTaskItem[]>(
    []
  );
  const [visible, setVisible] = useState(false);
  const saveShopSaleTaskHook = useRequest(API.saveShopSaleTask, {
    manual: true,
    throwOnError: true,
  });

  // 用于顾问前端搜索
  useEffect(() => {
    setAdvisersFiltered(shopTaskItem?.staffTaskList ?? []);
  }, [shopTaskItem]);

  const filterByAdviserName = (value: string) => {
    const list = (shopTaskItem?.staffTaskList ?? []).filter(
      (item: any) => item.staffName.indexOf(value) !== -1
    );
    setAdvisersFiltered(list);
  };

  // 前端更新编辑后的顾问分配任务
  const onOk = () => {
    adviserTaskEditRef.current?.submit((newTask) => {
      setShopTaskItem(newTask);
      setAdvisersFiltered(newTask?.staffTaskList); // 刷新列表
      setVisible(false);
    });
  };

  const handleGoBack = () => {
    history.goBack(); // todo 提示是否有未保存的修改
  };

  const handleSaveTask = async () => {
    const shopFormValue = form.getFieldsValue();
    const { taskId, ...other } = shopTaskItem!; // 因为门店零售任务分配表格数据填写时未修改 store
    saveShopSaleTaskHook
      .run({ ...other, id: taskId, ...shopFormValue })
      .then(() => {
        message.success("保存草稿成功");
      })
      .catch((error: any) => {
        message.error(error.message ?? "请求失败");
      });
  };

  const columns: ColumnsType<API.StaffTaskItem> = [
    {
      title: "销售顾问",
      width: 100,
      dataIndex: "staffName",
    },
    {
      title: "零售任务(台)",
      children: [
        {
          title: "合计",
          dataIndex: "taskCount",
          key: "taskCount",
        },
        {
          title: "新能源车",
          dataIndex: "newEnergyTaskCount",
          key: "newEnergyTaskCount",
        },
        {
          title: "传统燃油车",
          dataIndex: "fuelVehicleTaskCount",
          key: "fuelVehicleTaskCount",
        },
      ],
    },
    {
      title: "毛利任务(元)",
      children: [
        {
          title: "合计",
          dataIndex: "grossProfitTaskTotal",
          key: "grossProfitTaskTotal",
          render: (text: string, record: API.StaffTaskItem) => {
            return (record.taskCount * record.vehicleGrossProfitTask).toFixed(
              2
            );
          },
        },
        {
          title: "单车",
          dataIndex: "vehicleGrossProfitTask",
          key: "vehicleGrossProfitTask",
        },
      ],
    },
    {
      title: "线索到店成交(台)",
      width: 100,
      dataIndex: "clueDealTaskCount",
      key: "clueDealTaskCount",
    },
    {
      title: "首客试驾成交(台)",
      width: 100,
      dataIndex: "testDriveTaskCount",
      key: "testDriveTaskCount",
    },
    {
      title: "攻坚车任务(台)",
      width: 100,
      dataIndex: "tackCarTaskCount",
      key: "tackCarTaskCount",
    },
    {
      title: "车系任务(台)",
      width: 100,
      dataIndex: "seriesTaskCount",
      key: "seriesTaskCount",
    },
    {
      title: "操作",
      render: (text: string, record: API.StaffTaskItem) => {
        if (isReadOnly) return "-";
        return (
          <a
            onClick={() => {
              setEditAdviser(cloneDeep(record)); // 注意对象引用
              setVisible(true);
            }}
          >
            编辑
          </a>
        );
      },
    },
  ];

  return (
    <>
      <Row
        align="middle"
        justify="start"
        style={{ marginBottom: 20, marginTop: 14 }}
      >
        <Input.Search
          allowClear
          placeholder="顾问名称"
          style={{ width: 260, marginLeft: 15 }}
          onSearch={filterByAdviserName}
        />
      </Row>
      <Table
        columns={columns}
        dataSource={[...advisersFiltered]}
        pagination={false}
        rowKey="id"
        loading={false}
      />
      <Row align="middle" justify="center" style={{ marginTop: 50 }}>
        <Button onClick={handleGoBack}>返回列表</Button>
        {!isReadOnly && (
          <Button
            type="primary"
            style={{ marginLeft: 10 }}
            loading={saveShopSaleTaskHook.loading}
            onClick={handleSaveTask}
          >
            保存草稿
          </Button>
        )}
      </Row>
      <Modal
        width={1200}
        title={`当前选择顾问：${editAdviser?.staffName}`}
        open={visible}
        onOk={onOk}
        okText="确认"
        onCancel={() => setVisible(false)}
        maskClosable={false}
        keyboard={false}
        destroyOnClose
      >
        {/* @ts-ignore */}
        <AdviserTaskEdit ref={adviserTaskEditRef} />
      </Modal>
    </>
  );
}
