import { PlusOutlined } from "@ant-design/icons";
import {
  Button,
  Card,
  Col,
  Form,
  InputNumber,
  Modal,
  Row,
  message,
} from "antd";
import styles from "./index.less";
import React, { useState } from "react";
import { MAX_NUM } from "../entity";
import * as API from "../api";
import ShopSelectNew from "@/components/ShopSelectNew";

interface SaleTaskBatchSetProps {
  id: number;
  onCancel: () => void;
  onRefresh: () => void;
}

export default function SaleTaskBatchSet(props: SaleTaskBatchSetProps) {
  const [form] = Form.useForm();
  // 过滤各项已经选择的门店
  // const [selectedShopIds, setSelectedShopIds] = useState({
  //   grossProfit: [],
  //   tackCar: [],
  //   testDrive: [],
  // });

  const batchSetSaleTask = async (isAssignToAdviser: boolean) => {
    await form.validateFields();
    const values = form.getFieldsValue();
    const newValues = {};
    Array.from(Object.keys(values)).forEach((valueKey: any) => {
      if (values[valueKey]) {
        newValues[valueKey] = values[valueKey].map((valueItem: any) => ({
          taskAims: valueItem.taskAims,
          shopIdList: valueItem.shopIdList.map(
            (shopItem: any) => shopItem.shopId
          ),
        }));
      }
    });
    Modal.confirm({
      title: isAssignToAdviser
        ? "确认分配到门店和顾问吗？"
        : "确认分配到门店吗？",
      zIndex: 1002,
      onOk: async () => {
        const hide = message.loading("分配中，请稍候", 0);
        API.batchSetSaleTask({
          assignTask: isAssignToAdviser,
          orderTaskApplyId: props.id,
          ...newValues,
        })
          .then((res) => {
            message.success("分配成功");
            props.onRefresh();
          })
          .catch((error: any) => {
            message.error(error.message ?? "请求失败");
          })
          .finally(() => {
            hide();
          });
      },
    });
  };

  // const handleFormChange = (changedValues: any) => {
  //   const labelKey: any = Object.keys(changedValues)[0];
  //   const list: any = Object.values(changedValues)[0];
  //   console.log(list);
  //   if (!list[0]) return;
  //   if (Object.keys(list[0])[0] === "shopIdList") {
  //     const newSelectedIds = { ...selectedShopIds };
  //     newSelectedIds[labelKey] = Object.values(list[0])[0];
  //     setSelectedShopIds(newSelectedIds);
  //   }
  // };

  return (
    <Form
      form={form}
      name="sale-task-batch-set-form"
      autoComplete="off"
      // onValuesChange={handleFormChange}
    >
      <Form.List name="grossProfitTaskList">
        {(fields, { add, remove }) => (
          <Card>
            <Row
              align="middle"
              justify="space-between"
              style={{ marginBottom: 15 }}
            >
              <h4 className={styles.title}>单车毛利任务</h4>
              <Button type="link" onClick={() => add()} icon={<PlusOutlined />}>
                新增
              </Button>
            </Row>
            {fields.map(({ key, name, ...restField }) => (
              <Row gutter={16} key={key}>
                <Col className="gutter-row" span={6}>
                  <Form.Item
                    {...restField}
                    name={[name, "taskAims"]}
                    rules={[{ required: true, message: "请填写单车毛利任务" }]}
                  >
                    <InputNumber
                      formatter={(value) => `${value}元`}
                      parser={(value: any) => value.replace("元", "")}
                      min={0}
                      max={MAX_NUM}
                      style={{ width: "100%" }}
                      precision={2}
                      placeholder="请填写单车毛利任务"
                    />
                  </Form.Item>
                </Col>
                <Col className="gutter-row" span={15}>
                  <Form.Item
                    {...restField}
                    name={[name, "shopIdList"]}
                    rules={[{ required: true, message: "请选择适用门店" }]}
                  >
                    <ShopSelectNew
                      multiple
                      defaultOptions={{ bizTypes: "1" }}
                      placeholder="请选择适用门店"
                      // disabledShopIds={selectedShopIds.grossProfit}
                    />
                  </Form.Item>
                </Col>
                <Col className="gutter-row" span={3}>
                  <Button
                    type="link"
                    style={{ color: "#999" }}
                    onClick={() => remove(name)}
                  >
                    删除
                  </Button>
                </Col>
              </Row>
            ))}
          </Card>
        )}
      </Form.List>
      <Form.List name="testDriveTaskList">
        {(fields, { add, remove }) => (
          <Card style={{ marginTop: 20 }}>
            <Row
              align="middle"
              justify="space-between"
              style={{ marginBottom: 15 }}
            >
              <h4 className={styles.title}>首客试驾成交</h4>
              <Button type="link" onClick={() => add()} icon={<PlusOutlined />}>
                新增
              </Button>
            </Row>
            {fields.map(({ key, name, ...restField }) => (
              <Row gutter={16} key={key}>
                <Col className="gutter-row" span={6}>
                  <Form.Item
                    {...restField}
                    name={[name, "taskAims"]}
                    rules={[{ required: true, message: "请填写首客试驾成交" }]}
                  >
                    <InputNumber
                      formatter={(value) => `${value}台`}
                      parser={(value: any) => value.replace("台", "")}
                      min={0}
                      max={MAX_NUM}
                      style={{ width: "100%" }}
                      precision={0}
                      placeholder="请填写首客试驾成交"
                    />
                  </Form.Item>
                </Col>
                <Col className="gutter-row" span={15}>
                  <Form.Item
                    {...restField}
                    name={[name, "shopIdList"]}
                    rules={[{ required: true, message: "请选择适用门店" }]}
                  >
                    <ShopSelectNew
                      multiple
                      defaultOptions={{ bizTypes: "1" }}
                      placeholder="请选择适用门店"
                      // disabledShopIds={selectedShopIds.testDrive}
                    />
                  </Form.Item>
                </Col>
                <Col className="gutter-row" span={3}>
                  <Button
                    type="link"
                    style={{ color: "#999" }}
                    onClick={() => remove(name)}
                  >
                    删除
                  </Button>
                </Col>
              </Row>
            ))}
          </Card>
        )}
      </Form.List>
      <Form.List name="tackCarTaskList">
        {(fields, { add, remove }) => (
          <Card style={{ marginTop: 20 }}>
            <Row
              align="middle"
              justify="space-between"
              style={{ marginBottom: 15 }}
            >
              <h4 className={styles.title}>攻坚车任务</h4>
              <Button type="link" onClick={() => add()} icon={<PlusOutlined />}>
                新增
              </Button>
            </Row>
            {fields.map(({ key, name, ...restField }) => (
              <Row gutter={16} key={key}>
                <Col className="gutter-row" span={6}>
                  <Form.Item
                    {...restField}
                    name={[name, "taskAims"]}
                    rules={[{ required: true, message: "请填写攻坚车任务" }]}
                  >
                    <InputNumber
                      formatter={(value) => `${value}台`}
                      parser={(value: any) => value.replace("台", "")}
                      min={0}
                      max={MAX_NUM}
                      style={{ width: "100%" }}
                      precision={0}
                      placeholder="请填写攻坚车任务"
                    />
                  </Form.Item>
                </Col>
                <Col className="gutter-row" span={15}>
                  <Form.Item
                    {...restField}
                    name={[name, "shopIdList"]}
                    rules={[{ required: true, message: "请选择适用门店" }]}
                  >
                    <ShopSelectNew
                      multiple
                      defaultOptions={{ bizTypes: "1" }}
                      placeholder="请选择适用门店"
                      // disabledShopIds={selectedShopIds.tackCar}
                    />
                  </Form.Item>
                </Col>
                <Col className="gutter-row" span={3}>
                  <Button
                    type="link"
                    style={{ color: "#999" }}
                    onClick={() => remove(name)}
                  >
                    删除
                  </Button>
                </Col>
              </Row>
            ))}
          </Card>
        )}
      </Form.List>
      <Row align="middle" justify="center" style={{ marginTop: 20 }}>
        <Button onClick={props.onCancel}>取消</Button>
        <Button
          type="primary"
          style={{ marginLeft: 10 }}
          onClick={() => batchSetSaleTask(false)}
        >
          分配到门店
        </Button>
        <Button
          type="primary"
          style={{ marginLeft: 10 }}
          onClick={() => batchSetSaleTask(true)}
        >
          分配到门店和顾问
        </Button>
      </Row>
    </Form>
  );
}
