import React, { useEffect, useState } from "react";
import {
  Card,
  Table,
  DatePicker,
  Row,
  message,
  Input,
  Button,
  Modal,
} from "antd";
import * as API from "./api";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { history } from "umi";
import moment, { Moment } from "moment";
import useInitial from "@/hooks/useInitail";
import { Provider, useStore } from "./store";
import ApprovalProgressModal from "@/pages/stock/AdvanceProgress/components/ApproveModal";
import EntryTaskPreview from "./components/EntryTaskPreview";
import { OrderTaskApprovalType } from "./entity";
import AdviserTaskPreview from "./components/AdviserTaskPreview";
import SeriesTaskPreview from "./components/SeriesTaskPreview";
import ApproveModal from "@/pages/order3/Common/ApproveModal";
import SaleTaskAutoAssign from "./components/SaleTaskAutoAssign";
import SaleTaskBatchSet from "./components/SaleTaskBatchSet";
import { ColumnsType } from "antd/es/table";

export default () => (
  <Provider>
    <SaleTaskList />
  </Provider>
);

function SaleTaskList() {
  const { isReadOnly, setShopTaskItem, setIsReadOnly } = useStore();
  const [approve, setApprove] = useState({ visible: false, orderNo: "" });
  const [approveOpen, setApproveOpen] = useState(false);
  const [targetMonth, setTargetMonth] = useState(moment());
  const [etpVisible, setEtpVisible] = useState(false);
  const [previewTaskParams, setPreviewTaskParams] = useState({});
  const [atpVisible, setAtpVisible] = useState(false);
  const [adviserTaskParams, setAdviserTaskParams] = useState({});
  const [stpVisible, setStpVisible] = useState(false);
  const [seriesTaskParams, setSeriesTaskParams] = useState({});

  const [autoVisible, setAutoVisible] = useState(false);
  const [batchVisible, setBatchVisible] = useState(false);

  const { data, loading, setParams } = useInitial(
    API.getSaleTaskApi,
    {} as API.GetSaleTaskApiRes,
    {
      taskDate: targetMonth.valueOf(),
    }
  );

  useEffect(() => {
    setIsReadOnly(!data.canModified);
  }, [data]);

  const handleChangeMonth = (date: Moment | null) => {
    setTargetMonth(moment(date));
    setParams({ taskDate: moment(date).valueOf() }, true);
  };

  const goToEditPage = (record: API.ShopTaskItem) => {
    setShopTaskItem(record);
    history.push({
      pathname: "/order3/saleTask/edit",
      query: {
        readOnly: isReadOnly ? "1" : "0",
        shopId: String(record.shopId),
        taskDate: String(targetMonth.valueOf()),
      },
    });
  };

  // 查看销顾任务
  const goToAdviserPage = (record: API.ShopTaskItem) => {
    history.push({
      pathname: "/order3/saleTask/edit",
      query: {
        readOnly: isReadOnly ? "1" : "0",
        shopId: String(record.shopId),
        taskDate: String(targetMonth.valueOf()),
        currTab: "2",
      },
    });
  };

  // 查看流程进度
  const viewProcess = () => {
    setApprove({
      visible: true,
      orderNo: data.approvalNumber,
    });
  };

  const cancelSaleTask = () => {
    Modal.confirm({
      title: "提示",
      content: `确认撤销【${targetMonth.format("YYYY-MM")}】零售任务审批吗？`,
      zIndex: 1002,
      onOk: () => {
        API.cancelSaleTask({
          id: data.id,
        })
          .then((res) => {
            message.success("撤销成功");
          })
          .catch((error: any) => {
            message.error(error.message ?? "请求失败");
          })
          .finally(() => {
            setParams({}, true);
          });
      },
    });
  };

  const submitSaleTask = (parmas: any) => {
    const hide = message.loading("提交中", 0);
    API.submitSaleTask({
      id: data.id,
      ...parmas,
    })
      .then((res) => {
        message.success("提交成功");
      })
      .catch((error: any) => {
        message.error(error.message ?? "请求失败");
      })
      .finally(() => {
        hide();
        setParams({}, true);
      });
  };

  const handlePreviewTask = () => {
    const params: any = {
      id: data.id,
      orderTaskApprovalType: OrderTaskApprovalType.门店维度,
    };
    setPreviewTaskParams(params);
    setEtpVisible(true);
  };

  // 销顾任务
  const showAdviserModal = (
    record: API.TaskListItem,
    type: OrderTaskApprovalType
  ) => {
    const params: any = {
      id: data.id,
      taskId: record.id,
      orderTaskApprovalType: OrderTaskApprovalType.门店维度, // 只有门店有查看销顾任务
    };
    switch (type) {
      case OrderTaskApprovalType.门店维度:
        params.shopId = record.dataId;
        break;
      case OrderTaskApprovalType.销售顾问维度:
        params.staffId = record.dataId;
        break;
      case OrderTaskApprovalType.新车一级管理维度:
        params.firstManageId = record.dataId;
        break;
      case OrderTaskApprovalType.新车二级管理维度:
        params.secondManageId = record.dataId;
        break;
      case OrderTaskApprovalType.新车三级管理维度:
        params.thirdManageId = record.dataId;
        break;
      default:
        break;
    }
    setAdviserTaskParams(params);
    setAtpVisible(true);
  };

  // 销顾任务--查看车系任务
  const showSeriesModalByAdviser = (record: API.TaskListItem) => {
    const params = { ...adviserTaskParams } as any;
    params.taskId = record.id;
    params.orderTaskApprovalType = OrderTaskApprovalType.车系;
    params.staffId = record.dataId;
    setSeriesTaskParams(params);
    setStpVisible(true);
  };

  // 车系任务
  const showSeriesModal = (
    record: API.TaskListItem,
    type: OrderTaskApprovalType
  ) => {
    const params: any = {
      id: data.id,
      taskId: record.id,
      orderTaskApprovalType: OrderTaskApprovalType.车系,
    };
    switch (type) {
      case OrderTaskApprovalType.门店维度:
        params.shopId = record.dataId;
        break;
      case OrderTaskApprovalType.销售顾问维度:
        params.staffId = record.dataId;
        break;
      case OrderTaskApprovalType.新车一级管理维度:
        params.firstManageId = record.dataId;
        break;
      case OrderTaskApprovalType.新车二级管理维度:
        params.secondManageId = record.dataId;
        break;
      case OrderTaskApprovalType.新车三级管理维度:
        params.thirdManageId = record.dataId;
        break;
      default:
        break;
    }
    setSeriesTaskParams(params);
    setStpVisible(true);
  };

  const handleAutoAssignRefresh = () => {
    setAutoVisible(false);
    setParams({}, true);
  };
  const handleBatchSetRefresh = () => {
    setBatchVisible(false);
    setParams({}, true);
  };

  const columns: ColumnsType<API.ShopTaskItem> = [
    {
      title: "门店",
      width: 150,
      dataIndex: "shopName",
    },
    {
      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.ShopTaskItem) => {
            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.ShopTaskItem) => {
        return (
          <a
            onClick={() => {
              goToAdviserPage(record);
            }}
          >
            查看
          </a>
        );
      },
    },
    {
      title: "操作",
      render: (text: string, record: API.ShopTaskItem) => {
        return (
          <a
            onClick={() => {
              goToEditPage(record);
            }}
          >
            {isReadOnly ? "查看" : "编辑"}
          </a>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper title="零售任务分配">
      <Card>
        <Row
          align="middle"
          justify="space-between"
          style={{ marginBottom: 20 }}
        >
          <Row align="middle" justify="start" style={{ marginBottom: 20 }}>
            <DatePicker
              placeholder="月度"
              style={{ width: 260 }}
              picker="month"
              value={targetMonth}
              onChange={handleChangeMonth}
              allowClear={false}
            />
            <Input.Search
              allowClear
              placeholder="门店名称"
              style={{ width: 260, marginLeft: 15 }}
              onSearch={(v) => {
                setParams({ shopName: v }, true);
              }}
            />
          </Row>
          {!isReadOnly && (
            <Row align="middle" justify="start" style={{ marginBottom: 20 }}>
              <Button type="primary" onClick={() => setAutoVisible(true)}>
                零售任务快捷分配
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: 10 }}
                onClick={() => setBatchVisible(true)}
              >
                批量设置
              </Button>
            </Row>
          )}
        </Row>
        <Table
          rowKey="id"
          bordered
          loading={loading}
          columns={columns}
          dataSource={data.shopTaskList}
          pagination={false}
          scroll={{ y: 450 }}
          summary={() => {
            if (!data || !data.shopTaskList || data.shopTaskList.length <= 0) {
              return null;
            }
            return (
              <Table.Summary fixed="bottom">
                <Table.Summary.Row
                  style={{
                    background: "#FAFAFA",
                    fontSize: 18,
                    fontWeight: 500,
                  }}
                >
                  <Table.Summary.Cell index={1}>合计</Table.Summary.Cell>
                  <Table.Summary.Cell index={2}>
                    {data.totalTaskCount}
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={3}>
                    {data.newEnergyTaskCount}
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={4}>
                    {data.fuelVehicleTaskCount}
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={5}>-</Table.Summary.Cell>
                  <Table.Summary.Cell index={6}>-</Table.Summary.Cell>
                  <Table.Summary.Cell index={7}>
                    {data.clueDealTaskCount}
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={8}>
                    {data.testDriveTaskCount}
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={9}>
                    {data.tackCarTaskCount}
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={10}>
                    {data.seriesTaskCount}
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={11} />
                  <Table.Summary.Cell index={12} />
                </Table.Summary.Row>
              </Table.Summary>
            );
          }}
        />
        {data.revoke ? (
          <Row align="middle" justify="center" style={{ marginTop: 50 }}>
            <Button onClick={cancelSaleTask}>撤销</Button>
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={viewProcess}
            >
              审批进度
            </Button>
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={handlePreviewTask}
            >
              预览任务
            </Button>
          </Row>
        ) : (
          <Row align="middle" justify="center" style={{ marginTop: 50 }}>
            {!isReadOnly && (
              <Button type="primary" onClick={() => setApproveOpen(true)}>
                提交审批
              </Button>
            )}
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={handlePreviewTask}
            >
              预览任务
            </Button>
          </Row>
        )}
      </Card>
      <Modal
        width={1200}
        title="预览任务"
        open={etpVisible}
        onCancel={() => setEtpVisible(false)}
        destroyOnClose
        footer={null}
      >
        <EntryTaskPreview
          month={targetMonth}
          params={previewTaskParams}
          showAdviserModal={showAdviserModal}
          showSeriesModal={showSeriesModal}
        />
      </Modal>
      <Modal
        width={1200}
        title="销顾任务"
        open={atpVisible}
        onCancel={() => setAtpVisible(false)}
        destroyOnClose
        footer={null}
      >
        <AdviserTaskPreview
          params={adviserTaskParams}
          showSeriesModal={showSeriesModalByAdviser}
        />
      </Modal>
      <Modal
        width={600}
        title="车系任务"
        open={stpVisible}
        onCancel={() => setStpVisible(false)}
        destroyOnClose
        footer={null}
      >
        <SeriesTaskPreview params={seriesTaskParams} />
      </Modal>
      <Modal
        width={800}
        title="零售任务快捷分配"
        open={autoVisible}
        onCancel={() => setAutoVisible(false)}
        destroyOnClose
        footer={null}
        maskClosable={false}
      >
        <SaleTaskAutoAssign
          id={data.id}
          value={data.shopTaskList}
          onCancel={() => setAutoVisible(false)}
          onRefresh={handleAutoAssignRefresh}
        />
      </Modal>
      <Modal
        width={800}
        title="批量设置"
        open={batchVisible}
        onCancel={() => setBatchVisible(false)}
        destroyOnClose
        footer={null}
        maskClosable={false}
      >
        <SaleTaskBatchSet
          id={data.id}
          onCancel={() => setBatchVisible(false)}
          onRefresh={handleBatchSetRefresh}
        />
      </Modal>
      <ApprovalProgressModal
        visible={approve.visible}
        orderNo={approve.orderNo}
        onCancel={() => setApprove({ visible: false, orderNo: "" })}
      />
      <ApproveModal
        callback={submitSaleTask}
        open={approveOpen}
        setOpen={setApproveOpen}
      />
    </PageHeaderWrapper>
  );
}
