import React, { useEffect, useMemo, useState } from "react";
import {
  InputNumber,
  Divider,
  Form,
  message,
  Table,
  Button,
  Row,
  Tag,
  Modal,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import * as API from "../../../api";
import styles from "../index.less";
import { useStore } from "../../../store";
import _ from "lodash";
import EditableCell from "./EditableCell";
import SeriesModal from "./SeriesModal";
import { history, useRequest } from "umi";
import { MAX_NUM } from "../../../entity";

const { Column } = Table;

interface ShopTaskProps {
  form: any;
}

export default function ShopTask({ form }: ShopTaskProps) {
  const {
    shopTaskItem,
    isReadOnly,
    setShopSeriesRow,
    deleteShopSeriesRow,
    addShopSeriesRow,
  } = useStore();
  const [seriesForm] = Form.useForm();
  const [editingKey, setEditingKey] = useState(-1); // 编辑表格 key
  const [seriesVisible, setSeriesVisible] = useState(false);

  const saveShopSaleTaskHook = useRequest(API.saveShopSaleTask, {
    manual: true,
    throwOnError: true,
  });

  // 车系去重
  const selectedIds = useMemo(() => {
    if (!shopTaskItem) return [];
    return shopTaskItem.seriesTaskList.map((item) => String(item.seriesId));
  }, [shopTaskItem]);

  // 计算车系任务总数自动填写
  useEffect(() => {
    const total = shopTaskItem?.seriesTaskList.reduce(
      (total, currItem) => total + currItem.taskCount,
      0
    );
    form.setFieldValue("seriesTaskCount", total);
  }, [shopTaskItem]);

  const isEditing = (record: API.SeriesTaskItem) => {
    return record.seriesId === Number(editingKey);
  };

  const setSeriesRow = (id: number) => {
    seriesForm
      .validateFields()
      .then((row: any) => {
        setEditingKey(-1);
        setShopSeriesRow(id, row);
      })
      .catch((error: any) => {
        message.error(error.message ?? "表单校验失败");
      });
  };

  const editSeriesRow = (record: API.SeriesTaskItem) => {
    seriesForm.setFieldsValue({ ...record });
    setEditingKey(record.seriesId);
  };

  // 添加车系
  const handleSelectSeries = (values: any) => {
    addShopSeriesRow(values);
    setSeriesVisible(false);
  };

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

  const handleSaveTask = async () => {
    await form.validateFields();
    const values = form.getFieldsValue();
    const { taskId, ...other } = shopTaskItem!;
    saveShopSaleTaskHook
      .run({ ...other, ...values, id: taskId })
      .then(() => {
        message.success("保存草稿成功");
      })
      .catch((error: any) => {
        message.error(error.message ?? "请求失败");
      });
  };

  // 分配到门店和顾问
  const autoAssignOneShop = async () => {
    await form.validateFields();
    const values = form.getFieldsValue();
    Modal.confirm({
      title: (
        <span>
          确认分配到
          <span className="tip">全部门店和顾问</span>
          吗？
        </span>
      ),
      zIndex: 1002,
      onOk: async () => {
        const hide = message.loading("分配中，请稍候", 0);
        const { taskId, id, ...other } = shopTaskItem!;
        API.autoAssignOneShop({
          ...other,
          ...values,
          orderTaskApplyId: taskId,
          orderShopTaskId: id,
        })
          .then((res) => {
            message.success("分配成功");
          })
          .catch((error: any) => {
            message.error(error.message ?? "请求失败");
          })
          .finally(() => {
            hide();
          });
      },
    });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  const components = {
    body: {
      cell: EditableCell,
    },
  };

  return (
    <>
      <div style={{ width: 880, margin: "0 auto", paddingTop: 24 }}>
        <Form
          {...layout}
          labelAlign="left"
          form={form}
          initialValues={shopTaskItem!}
        >
          <Form.Item name="taskCount" label="零售任务：" required>
            <InputNumber
              formatter={(value) => `${value}台`}
              parser={(value: any) => value.replace("台", "")}
              min={0}
              max={MAX_NUM}
              style={{ width: "100%" }}
              disabled={isReadOnly}
              precision={0}
            />
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => {
              if (prevValues.taskCount !== currentValues.taskCount) {
                form.setFieldValue(
                  "clueDealTaskCount",
                  (
                    currentValues.taskCount *
                    ((shopTaskItem?.clueDealTaskRate ?? 100) / 100)
                  ).toFixed(2)
                );
              }
              return prevValues.taskCount !== currentValues.taskCount;
            }}
          >
            {() => {
              return (
                <Form.Item
                  name="clueDealTaskCount"
                  label="线索到店零售台数："
                  required
                >
                  <InputNumber
                    formatter={(value) => `${value}台`}
                    parser={(value: any) => value.replace("台", "")}
                    min={0}
                    max={MAX_NUM}
                    style={{ width: "100%" }}
                    disabled={isReadOnly}
                    precision={2}
                  />
                </Form.Item>
              );
            }}
          </Form.Item>
          <Form.Item
            name="newEnergyTaskCount"
            label="新能源车任务台数："
            required
            dependencies={["taskCount", "fuelVehicleTaskCount"]}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  const taskCount = getFieldValue("taskCount");
                  const fuelVehicleTaskCount = getFieldValue(
                    "fuelVehicleTaskCount"
                  );
                  if (
                    value >= 0 &&
                    fuelVehicleTaskCount + value === taskCount
                  ) {
                    return Promise.resolve();
                  }
                  return Promise.reject(
                    new Error(
                      "规则：新能源车任务台数 + 传统燃油车任务台数 = 零售任务台数"
                    )
                  );
                },
              }),
            ]}
          >
            <InputNumber
              formatter={(value) => `${value}台`}
              parser={(value: any) => value.replace("台", "")}
              min={0}
              max={MAX_NUM}
              style={{ width: "100%" }}
              disabled={isReadOnly}
              precision={0}
            />
          </Form.Item>

          <Form.Item
            name="fuelVehicleTaskCount"
            label="传统燃油车任务台数："
            required
            dependencies={["taskCount", "newEnergyTaskCount"]}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  const taskCount = getFieldValue("taskCount");
                  const newEnergyTaskCount =
                    getFieldValue("newEnergyTaskCount");
                  if (value >= 0 && newEnergyTaskCount + value === taskCount) {
                    return Promise.resolve();
                  }
                  return Promise.reject(
                    new Error(
                      "规则：新能源车任务台数 + 传统燃油车任务台数 = 零售任务台数"
                    )
                  );
                },
              }),
            ]}
          >
            <InputNumber
              formatter={(value) => `${value}台`}
              parser={(value: any) => value.replace("台", "")}
              min={0}
              max={MAX_NUM}
              style={{ width: "100%" }}
              disabled={isReadOnly}
              precision={0}
            />
          </Form.Item>
          <Form.Item
            name="vehicleGrossProfitTask"
            label="单车毛利任务："
            required
          >
            <InputNumber
              formatter={(value) => `${value}元`}
              parser={(value: any) => value.replace("元", "")}
              min={0}
              max={MAX_NUM}
              style={{ width: "100%" }}
              disabled={isReadOnly}
              precision={2}
            />
          </Form.Item>
          <Form.Item
            name="testDriveTaskCount"
            label="首客试驾成交任务台数："
            required
          >
            <InputNumber
              formatter={(value) => `${value}台`}
              parser={(value: any) => value.replace("台", "")}
              min={0}
              max={MAX_NUM}
              style={{ width: "100%" }}
              disabled={isReadOnly}
              precision={0}
            />
          </Form.Item>
          <Form.Item name="tackCarTaskCount" label="攻坚车任务台数：" required>
            <InputNumber
              formatter={(value) => `${value}台`}
              parser={(value: any) => value.replace("台", "")}
              min={0}
              max={MAX_NUM}
              style={{ width: "100%" }}
              disabled={isReadOnly}
              precision={0}
            />
          </Form.Item>
          <Form.Item name="seriesTaskCount" label="车系任务台数：" required>
            <InputNumber
              formatter={(value) => `${value}台`}
              parser={(value: any) => value.replace("台", "")}
              min={0}
              max={MAX_NUM}
              style={{ width: "100%" }}
              precision={0}
              disabled
            />
          </Form.Item>
        </Form>
      </div>
      <Divider />
      <div style={{ width: 880, margin: "0 auto" }}>
        <Row
          align="middle"
          justify="space-between"
          style={{ marginBottom: 20 }}
        >
          <h2 className={styles.carTask}>车系任务</h2>
          {!isReadOnly && (
            <Button
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setSeriesVisible(true);
              }}
            >
              添加车系
            </Button>
          )}
        </Row>
        <Form form={seriesForm} component={false}>
          <Table
            scroll={{ y: 400 }}
            rowKey="seriesId"
            rowClassName={() => "editable-cell"}
            pagination={false}
            components={components}
            dataSource={[...shopTaskItem?.seriesTaskList!]}
          >
            <Column
              title="车系"
              dataIndex="seriesName"
              render={(value, record: API.SeriesTaskItem) => {
                return (
                  <Row align="middle" justify="start">
                    <span>{value}</span>
                    {record.newEnergy && (
                      <Tag
                        style={{ marginBottom: 5, marginLeft: 7 }}
                        color="green"
                      >
                        新能源
                      </Tag>
                    )}
                  </Row>
                );
              }}
            />
            <Column
              title="零售任务（台）"
              dataIndex="taskCount"
              onCell={(record: API.SeriesTaskItem) => ({
                record,
                inputType: "number",
                dataIndex: "taskCount",
                title: "零售任务（台）",
                editing: isEditing(record),
              })}
            />
            {!isReadOnly && (
              <Column
                width={120}
                title="操作"
                render={(text, record: API.SeriesTaskItem) => {
                  const editable = isEditing(record);
                  return (
                    <div>
                      {editable ? (
                        <span>
                          <a onClick={() => setSeriesRow(record.seriesId)}>
                            确认
                          </a>
                          <Divider type="vertical" />
                          <a
                            style={{ color: "#999" }}
                            onClick={() => setEditingKey(-1)}
                          >
                            取消
                          </a>
                        </span>
                      ) : (
                        <span>
                          <a onClick={() => editSeriesRow(record)}>编辑</a>
                          <Divider type="vertical" />
                          <a
                            style={{ color: "#999" }}
                            onClick={() => deleteShopSeriesRow(record.seriesId)}
                          >
                            删除
                          </a>
                        </span>
                      )}
                    </div>
                  );
                }}
              />
            )}
          </Table>
        </Form>
      </div>
      <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>
        )}
        {!isReadOnly && (
          <Button
            type="primary"
            style={{ marginLeft: 10 }}
            onClick={autoAssignOneShop}
          >
            分配到门店和顾问
          </Button>
        )}
      </Row>
      <SeriesModal
        visible={seriesVisible}
        selectedIds={selectedIds}
        onOk={handleSelectSeries}
        onCancel={() => {
          setSeriesVisible(false);
        }}
      />
    </>
  );
}
