import React, { useState, useEffect } from "react";
import { CheckCircleOutlined } from '@ant-design/icons';
import {
  Checkbox,
  Button,
  Form,
  Radio,
  InputNumber,
  Row,
  DatePicker,
  Select,
  message,
  Spin,
  Card,
  Divider,
  Typography,
  Space,
} from "antd";
import useInitial from "@/hooks/useInitail";
import { getShopApi } from "@/common/api";
import CarSelect from "./CarSelect";
import { transformDTO, transformFormData } from "../../entity";
import { useStore } from "@/pages/mkt/ActivityCreate/index";
import {
  saveSalePromotionApi,
  saveScopeChangeApi,
  getSalePromotionDetail,
  fetchActivityCount,
  fetchCustomerCount,
} from "../../api";
import _ from "lodash";
import TargetCustomer from "./TargetCustomer";

const { Option } = Select;

function Index() {
  const [form] = Form.useForm();
  const { baseInfo, readOnly, setJoinShops } = useStore();
  const { bizType, activityNo, activityType, changeEnable } = baseInfo;
  const [disable, setDisable] = useState(false);
  const [JoinLimit, setGoalJoinLimit] = useState<number>();
  const [nonGoalLimit, setNonGoalLimit] = useState<{ nonGoalJoin?: boolean, publicity?: boolean }>({});
  const { data, errMsg, loading } = useInitial(
    getSalePromotionDetail,
    {},
    { activityNo, change: changeEnable }
  );
  const { data: shopsList, setParams: setShopParams } = useInitial(getShopApi, [], { bizType });
  const [saveLoading, setSaveLoading] = useState(false);
  const [count, setCount] = useState();

  useEffect(() => {
    if (errMsg) {
      //接口未报错
      return;
    }
    data.goalJoinLimit && setGoalJoinLimit(data.goalJoinLimit);
    setNonGoalLimit({
      nonGoalJoin: data.nonGoalJoin,
      publicity: data.publicity
    });
    const result = transformFormData(data, bizType, activityType);
    form.setFieldsValue({
      ...result,
    });
    setCount(undefined);
  }, [data, bizType]);

  useEffect(() => {
    bizType && setShopParams({ bizType }, true);
  }, [bizType]);

  /** 获取门店id */
  function getShopIds() {
    const shopIds = form.getFieldValue("authShops")?.map(
      (item: { label: string; value: number; key: string }) => item.value
    );
    return shopIds.join(",");
  }

  // 查看售前满足条件人数
  function crmPersonCount(type: number, value: number) {
    const pa: ExternalPromotion.ActivityCountParams = {
      archivesState: type,
      minCarPurchaseIntention: value,
    };
    const shopIds = getShopIds();
    if (shopIds) {
      pa.shopIds = shopIds;
      pa.seriesIds = (form.getFieldValue("authCars") || []).map(item => item.seriesId).join(",");
    }
    fetchActivityCount(pa)
      .then((res) => {
        const { data } = res;
        setCount(data);
      })
      .catch((err) => message.error(err.message));
  }

  // 查看售后满足条件人数
  function asCrmPersonCount(key: number) {
    let pa: ExternalPromotion.CustomerCountParams = {};
    const shopIds = getShopIds();
    if (shopIds) {
      pa.shopList = shopIds;
    }
    const keepType = form.getFieldValue("conditions")[key].afterConditionType;
    if (keepType === 2 || keepType === 4) {
      pa.type = keepType;
    }
    fetchCustomerCount(pa)
      .then((res) => {
        const { data } = res;
        setCount(data);
      })
      .catch((err) => message.error(err.message));
  }

  // 查看售后满足条件人数2(保有客)
  function asCrmPersonCount2(key: number, detail: any[], list: any[]) {
    let pa: ExternalPromotion.CustomerCountParams = {};
    const shopIds = getShopIds();
    if (shopIds) {
      pa.shopList = shopIds;
    }

    /** 限制条件选择结果 */
    const conditionRes = form.getFieldValue("conditions")[key].andCondition;
    if (conditionRes === true || conditionRes === false) {
      pa.andCondition = conditionRes;
    }
    /** 保有客=》保有客 */
    list.length &&
      detail.length &&
      detail.forEach((item) => {
        switch (item) {
          case 0:
            pa.arrivalMileage = `${list[0].mileageFrom},${list[0].mileageTo}`;
            break;
          case 1:
            pa.ageLimit = `${list[0].ageLimitForm},${list[0].ageLimitTo}`;
            break;
          case 2:
            pa.level = list[0].level;
            break;
          default:
            break;
        }
      });
    fetchCustomerCount(pa)
      .then((res) => {
        const { data } = res;
        setCount(data);
      })
      .catch((err) => message.error(err.message));
  }
  /**保存表单数据*/
  const _onOk = (values: any) => {
    form
      .validateFields()
      .then((fileds) => {
        const { conditions } = fileds;
        let res = true;
        if (
          bizType === 2 &&
          conditions[0].afterConditionType === 9 &&
          conditions.length
        ) {
          res = conditions.some((item: any) => {
            if (item.mileageFrom) {
              if (!item.mileageTo) {
                message.error("请输入进展里程结束值", 2);
                return false;
              } else if (Number(item.mileageFrom) > Number(item.mileageTo)) {
                message.error("进站里程结束值不能小于起始值", 2);
                return false;
              }
            }
            if (item.ageLimitForm) {
              if (!item.ageLimitTo) {
                message.error("请输入车辆年限结束值", 2);
                return false;
              } else if (Number(item.ageLimitForm) > Number(item.ageLimitTo)) {
                message.error("车辆年限结束值不能小于起始值", 2);
                return false;
              }
            }
            return true;
          });
        }

        if (res) {
          let result = transformDTO(fileds, bizType);
          // return;
          result.activityNo = activityNo;
          if (bizType === 2) {
            result.nonGoalJoin = false;
          }
          setSaveLoading(true);
          const currentApi = changeEnable ? saveScopeChangeApi : saveSalePromotionApi;
          currentApi(result).then((res) => {
              message.success("活动范围保存成功");
              setJoinShops(fileds.authShops.map((item: { value: number }) => item.value).join(","));
            })
            .catch((error) => message.error(error.message))
            .finally(() => setSaveLoading(false));
        }
      })
      .catch((err) => console.log(err.message));
  };

  //售前--》潜客：
  const renderBeforeSale = () => {
    return (
      <Card title="">
        <Form.List name="conditions">
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name, ...restField }, index) => (
                <div key={key}>
                  <p>潜客：</p>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "flex-start",
                      marginLeft: 30,
                      alignItems: "baseline",
                    }}
                  >
                    <span style={{ marginRight: 10 }}> 智能评级≥</span>
                    <Form.Item
                      name={[name, "judgeValue"]}
                      style={{ display: "inline-block" }}
                      rules={[
                        { required: true, message: "请输入" },
                      ]}
                    >
                      <InputNumber min={0} max={100} precision={0} style={{ width: 200 }} disabled={readOnly} />
                    </Form.Item>
                    <span>%</span>
                  </div>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "flex-start",
                      marginLeft: 30,
                      alignItems: "baseline",
                    }}
                  >
                    <Form.Item
                      noStyle
                      shouldUpdate={(prevValues, currentValues) => prevValues.conditions !== currentValues.conditions}
                    >
                      {({ getFieldValue }) => {
                        const value =
                          getFieldValue("conditions")[key].judgeValue;
                        if (value != null) {
                          return (
                            <Button
                              type="primary"
                              onClick={() => crmPersonCount(2, value)}
                              style={{ marginRight: 20 }}
                            >
                              查看满足客户数
                            </Button>
                          );
                        }
                      }}
                    </Form.Item>
                    {count !== undefined && <p>客户数：{count}人</p>}
                  </div>
                </div>
              ))}
            </>
          )}
        </Form.List>
      </Card>
    );
  };

  //售后--》流失预警线索
  const renderLossWarningClue = (name: number, key: number) => {
    // 判断类型;
    return (
      <>
        <p>流失预警线索展示：</p>
        <Row>
          <span> 截止</span>
          <Form.Item
            name={[name, "lossWarningClue"]}
            style={{ display: "inline-block" }}
            rules={[{ required: true, message: "请选择日期" }]}
          >
            <DatePicker format="YYYY.MM.DD" disabled={readOnly} />
          </Form.Item>
          <span>号前线索池中未成交的客户</span>
        </Row>
        {/* 查看档案数量按钮 */}
        <div
          style={{
            display: "flex",
            justifyContent: "flex-start",
            marginLeft: 30,
            alignItems: "baseline",
          }}
        >
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.conditions !== currentValues.conditions}
          >
            {({ getFieldValue }) => {
              const value = getFieldValue("conditions")[key].lossWarningClue;
              if (value) {
                return (
                  <Button
                    type="primary"
                    onClick={() => asCrmPersonCount(key)}
                    style={{ marginRight: 20 }}
                  >
                    查看满足客户数
                  </Button>
                );
              }
            }}
          </Form.Item>
          {count !== undefined && <p>客户数：{count}人</p>}
        </div>
      </>
    );
  };

  // 售后==》续保线索
  function renderRenewalClue(name: number, key: number) {
    return (
      <div>
        <p>续保线索展示：</p>
        <Row>
          <span> 截止</span>
          <Form.Item
            name={[name, "renewalClue"]}
            style={{ display: "inline-block" }}
            rules={[{ required: true, message: "请选择日期" }]}
          >
            <DatePicker format="YYYY.MM.DD" disabled={readOnly} />
          </Form.Item>
          <span>号前线索池中未成交的客户</span>
        </Row>
        {/* 查看档案数量按钮 */}
        <div
          style={{
            display: "flex",
            justifyContent: "flex-start",
            marginLeft: 30,
            alignItems: "baseline",
          }}
        >
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.conditions !== currentValues.conditions}
          >
            {({ getFieldValue }) => {
              const value = getFieldValue("conditions")[key].renewalClue;
              if (value) {
                return (
                  <Button
                    type="primary"
                    onClick={() => asCrmPersonCount(key)}
                    style={{ marginRight: 20 }}
                  >
                    查看满足客户数
                  </Button>
                );
              }
            }}
          </Form.Item>
          {count !== undefined && <p>客户数：{count}人</p>}
        </div>
      </div>
    );
  }
  /**
   * 售后--》 保有客
   */
  const renderAfterSale = () => {
    return (
      <>
        <Card title="">
          <Form.List name="conditions">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }, index) => {
                  return (
                    <div key={key}>
                      <Form.Item
                        label="保有客:"
                        name={[name, "afterConditionType"]}
                        rules={[{ required: true, message: "请选择" }]}
                        style={{ marginBottom: 30 }}
                      >
                        <Radio.Group
                          disabled={readOnly}
                          onChange={(e) => {
                            setCount(undefined);
                          }}
                        >
                          <Radio value={2}>流失预警线索 </Radio>
                          <Radio value={4}>续保线索 </Radio>
                          <Radio value={9}>保有客</Radio>
                        </Radio.Group>
                      </Form.Item>

                      <Form.Item
                        {...restField}
                        noStyle
                        shouldUpdate={(prevValues, currentValues) => prevValues.conditions !== currentValues.conditions}
                      >
                        {({ getFieldValue }) => {
                          if (
                            getFieldValue("conditions")[key].afterConditionType
                          ) {
                            let value =
                              getFieldValue("conditions")[key]
                                .afterConditionType;

                            let result = null;
                            if (value === 2) {
                              result = renderLossWarningClue(name, key);
                            }
                            if (value === 4) {
                              result = renderRenewalClue(name, key);
                            }
                            if (value === 9) {
                              // result = renderKeepGuest(name, key);
                              result = renderKeepGuest(name, index);
                              // index;
                            }
                            return result;
                          }
                        }}
                      </Form.Item>
                    </div>
                  );
                })}
              </>
            )}
          </Form.List>
        </Card>
      </>
    );
  };

  //售后--》 保有客 =》 保有客
  const renderKeepGuest = (name: number, key: number) => {
    // 判断类型;
    return (
      <>
        <Form.Item
          name={[name, "andCondition"]}
          label="条件限制"
          rules={[{ required: true, message: "请选择" }]}
        >
          <Select
            style={{ width: "100%" }}
            disabled={readOnly}
            allowClear
            onChange={() => setCount(undefined)}
          >
            <Option value>并且</Option>
            <Option value={false}>或者</Option>
          </Select>
        </Form.Item>
        <Form.Item
          name={[name, "detail"]}
          label="条件限制"
          rules={[{ required: true, message: "请选择" }]}
        >
          <TargetCustomer
            form={form}
            name={name}
            readOnly={readOnly}
            data={data}
            bizType={bizType}
            // const [count, setCount] = useState();
            setCount={setCount}
          />
        </Form.Item>
        {/* 查看档案数量按钮 */}
        <div
          style={{
            display: "flex",
            justifyContent: "flex-start",
            marginLeft: 30,
            alignItems: "baseline",
          }}
        >
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.conditions !== currentValues.conditions}
          >
            {({ getFieldValue }) => {
              const list = form.getFieldValue("conditions");
              const detail = getFieldValue("conditions")[key].detail;
              let res = null;
              list.length && detail &&
                detail.length &&
                detail.forEach((item) => {
                  switch (item) {
                    case 0:
                      if (
                        list[0].mileageFrom != undefined &&
                        list[0].mileageTo != undefined
                      ) {
                        res = true;
                      } else {
                        res = false;
                      }
                      break;
                    case 1:
                      if (
                        list[0].ageLimitForm != undefined &&
                        list[0].ageLimitTo != undefined
                      ) {
                        res = true;
                      } else {
                        res = false;
                      }
                      break;
                    case 2:
                      if (list[0].level != undefined) {
                        res = true;
                      } else {
                        res = false;
                      }
                      break;
                    default:
                      break;
                  }
                });
              if (res) {
                return (
                  <Button
                    type="primary"
                    onClick={() => asCrmPersonCount2(key, detail, list)}
                    style={{ marginRight: 20 }}
                  >
                    查看满足客户数
                  </Button>
                );
              }
            }}
          </Form.Item>
          {count !== undefined && <p>客户数：{count}人</p>}
        </div>
      </>
    );
  };
  return (
    <>
      {loading && (
        <Spin spinning={loading}>
          <div>加载中……</div>
        </Spin>
      )}
      {errMsg && <div>{errMsg || "加载错误"}</div>}
      {!loading && !errMsg && (
        <Form
          form={form}
          onFinish={_onOk}
          initialValues={{
            nonGoalJoin: false,
            publicity: ![5, 6, 9].includes(activityType || 0),
            goalType: bizType === 2 ? 2 : undefined,
            conditions: [
              {
                judgeType: 2,
                bizType,
                customerType: bizType === 2 ? 3 : 2,
              },
            ],
          }}
          style={{ marginLeft: 100, width: "80%" }}
        >
          <Form.Item
            label="参与门店："
            name="authShops"
            rules={[{ required: true, message: "请选择门店" }]}
          >
            <Select
              mode="multiple"
              disabled={readOnly && !changeEnable}
              optionFilterProp="children"
              allowClear
              showSearch
              placeholder="请选择"
              labelInValue
              onChange={() => setCount(undefined)}
              dropdownRender={menu => (
                <>
                  {menu}
                  <Divider style={{ margin: '8px 0' }} />
                  <Space align="center" style={{ padding: '0 8px 4px' }}>
                    <Typography.Link onClick={() => form.setFieldsValue({ 'authShops': shopsList.map((item => ({ value: item.id, label: item.name }))) })} style={{ whiteSpace: 'nowrap' }}>
                      <CheckCircleOutlined style={{ marginRight: 10 }} />
                      一键全选
                    </Typography.Link>
                  </Space>
                </>
              )}
            >
              {shopsList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          {bizType === 1 && (
            <Form.Item
              label="车辆"
              name="joinSeriesType"
              style={{ marginTop: 30 }}
              rules={[{ required: true, message: "请选择车辆范围" }]}
            >
              <Radio.Group disabled={readOnly}>
                <Radio value={1}>全部车辆 </Radio>
                <Radio value={2}>部分车辆</Radio>
              </Radio.Group>
            </Form.Item>
          )}

          {/* 部分车辆*/}
          {bizType === 1 && (
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.joinSeriesType !== currentValues.joinSeriesType}
            >
              {({ getFieldValue }) => (getFieldValue("joinSeriesType") === 2 ? (
                <Form.Item
                  name="authCars"
                  rules={[{ required: true, message: "选择车辆信息" }]}
                >
                  <CarSelect disabled={readOnly && !changeEnable} />
                </Form.Item>
              ) : null)}
            </Form.Item>
          )}

          {/* 选择业态之后，才能选择目标客户 */}
          {bizType && (
            <>
              <div style={{ marginTop: 30, marginBottom: 15 }}>*目标邀约客户：</div>
              <div style={{ paddingLeft: 30 }}>
                <Form.Item
                  name="goalType"
                  rules={[{ required: true, message: "请选择目标客户" }]}
                >
                  <Radio.Group
                    disabled={readOnly || bizType === 2}
                    onChange={(e) => {
                      setCount(undefined);
                      if (e.target.value === 1) {
                        setDisable(true);
                        form.setFieldsValue({ nonGoalJoin: true, nonGoalBrowse: true });
                      } else {
                        setDisable(false);
                        form.setFieldsValue({
                          //售前
                          conditions: [
                            {
                              judgeType: 2,
                              bizType,
                              customerType: bizType === 2 ? 3 : 2,
                            },
                          ],
                        });
                      }
                    }}
                  >
                    <Radio value={2}>有具体活动邀约对象</Radio>
                    <Radio value={1}>无具体活动邀约对象</Radio>
                  </Radio.Group>
                </Form.Item>
              </div>
            </>
          )}
          {bizType === 2 && (
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.goalType !== currentValues.goalType}
            >
              {({ getFieldValue }) => (getFieldValue("goalType") === 2 ? renderAfterSale() : null)}
            </Form.Item>
          )}

          {bizType === 1 && (
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.goalType !== currentValues.goalType}
            >
              {({ getFieldValue }) => (getFieldValue("goalType") === 2 ? renderBeforeSale() : null)}
            </Form.Item>
          )}
          <div style={{ marginTop: 30, marginBottom: 15 }}>*活动报名资格：</div>
          {bizType !== 2 && (
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.goalType !== currentValues.goalType}
            >
              {({ getFieldValue }) => (getFieldValue("goalType") === 2 ? (
                <Form.Item name="goalJoinLimit" rules={[{ required: true, message: "请选择活动报名条件" }]}>
                  <Radio.Group
                    disabled={readOnly && !changeEnable}
                    onChange={(v) => {
                      setGoalJoinLimit(v.target.value);
                      if (v.target.value === 1) {
                        form.setFieldsValue({ nonGoalJoin: false });
                        setDisable(true);
                      } else {
                        setDisable(false);
                      }
                    }}
                    options={[
                      {
                        label: <div><div>仅限截止活动发布时的目标客户</div> <div style={{ fontSize: 12, color: '#999' }}>（<span style={{ color: 'red' }}>不含</span>后续满足条件的目标客户）</div></div>,
                        value: 1
                      },
                      {
                        label: <div><div>符合条件的目标客户都可参加</div> <div style={{ fontSize: 12, color: '#999' }}>（<span style={{ color: 'red' }}>含</span>后续满足条件的目标客户）</div></div>,
                        value: 2
                      },
                    ]}
                  />
                </Form.Item>
              ) : null)}
            </Form.Item>
          )}
          {/* 滚动进池客户可享受外促政策 */}
          {bizType !== 2 && (
            <Form.Item name="nonGoalJoin" valuePropName="checked">
              <Checkbox
                disabled={(readOnly && !changeEnable) || disable || JoinLimit === 1}
                onChange={(v) => {
                  if (v.target.checked) {
                    form.setFieldsValue({ nonGoalBrowse: true });
                  }
                  setNonGoalLimit({ ...nonGoalLimit, nonGoalJoin: v.target.checked });
                }}
              >
                非目标客户可享受外促政策
              </Checkbox>
            </Form.Item>
          )}
          <div style={{ marginTop: 35, color: '#666' }}>*活动页面展示（C端---{'>'}霏车车小程序）</div>
          <Form.Item name="publicity" valuePropName="checked">
            <Checkbox
              disabled={(readOnly && !changeEnable) || [5, 6, 9].includes(activityType || 0)}
              onChange={(v) => {
                if (v.target.checked) {
                  form.setFieldsValue({ nonGoalBrowse: true });
                }
                setNonGoalLimit({ ...nonGoalLimit, publicity: v.target.checked });
              }}
            >
              在广告区展示
            </Checkbox>
          </Form.Item>
          <div style={{ marginTop: 30, color: '#666' }}>*车系详情中＂查看优惠＂页面展示活动信息</div>
          <Form.Item name="nonGoalBrowse" valuePropName="checked">
            <Checkbox disabled={(readOnly && !changeEnable) || (disable && JoinLimit !== 1) || (!!nonGoalLimit.nonGoalJoin || !!nonGoalLimit.publicity)}> 非目标客户可查看</Checkbox>
          </Form.Item>

          <Form.Item style={{ marginTop: 30, textAlign: "center" }}>
            <Button
              htmlType="submit"
              type="primary"
              loading={saveLoading}
              disabled={readOnly && !changeEnable}
            >
              保存活动范围
            </Button>
          </Form.Item>
        </Form>
      )}
    </>
  );
}

export default () => <Index />;
