import { FC, useEffect, useRef, useState } from "react";
import "./index.scss";
import { Button, message } from "antd";
import { useNavigate } from "react-router-dom";
import dayJs from "dayjs";
import qs from "query-string";
import BaseInfo from "./components/baseInfo";
import ShareCouponInfo from "./components/shareCouponInfo";
import SharedCouponInfo from "./components/sharedCouponInfo";
import { MakeManageAPI } from "~/api/modules/makeManage";
import { MakeItemEntity } from "~/api/interface/makeManage";
import { CouponManageAPI } from "~/api";

const SplitCouponOperate: FC<any> = (props) => {
  const history = useNavigate();
  const baseInfoRef = useRef<any>();
  const shareCouponRef = useRef<any>();
  const sharedCouponRef = useRef<any>();

  // 品牌列表数据
  const [makeList, setMakeList] = useState<MakeItemEntity[]>([]);
  // 品牌-列表
  const getMakeList = () => {
    MakeManageAPI.getListBrandInfo({ pageNo: 1, pageSize: 999999 }).then(
      ({ result }) => {
        setMakeList(result.list || []);
      }
    );
  };
  const [splitCouponId, setSplitCouponId] = useState<string>("");
  // 详情
  const getSplitCouponDetail = (couponId: string) => {
    CouponManageAPI.getPageActivityList({
      couponId,
      pageNo: 1,
      pageSize: 10,
      useType: 2,
    }).then(({ result }) => {
      if (result.list[0]) {
        (shareCouponRef.current as any).setCouponType(
          result.list[0].couponType
        );
        const { beSharedCoupon } = result.list[0];
        (sharedCouponRef.current as any).setCouponType(
          beSharedCoupon.couponType
        );
        (baseInfoRef.current as any).getForm().setFieldsValue({
          couponName: result.list[0].couponName,
        });
        (shareCouponRef.current as any).getForm().setFieldsValue({
          primaryKey: (result.list[0].primaryKey as any).split(",").map(Number),
          time: [
            dayJs(result.list[0].useStartTime),
            dayJs(result.list[0].useEndTime),
          ],
          couponMoney: result.list[0].couponMoney,
          couponType: result.list[0].couponType,
          minPrice: result.list[0].minPrice || undefined,
          couponDiscount: result.list[0].couponDiscount || undefined,
          verificationType: result.list[0].verificationType ? 1 : 0,
          couponTotal: result.list[0].couponTotal,
          restrictedAccess: result.list[0].restrictedAccess,
          peopleNumber: result.list[0].peopleNumber,
          userTag: beSharedCoupon.userTag || undefined,
        });
        (sharedCouponRef.current as any).getForm().setFieldsValue({
          beSharedPrimaryKey: (beSharedCoupon.primaryKey as any)
            .split(",")
            .map(Number),
          beSharedCouponMoney: beSharedCoupon.couponMoney,
          beSharedCouponType: beSharedCoupon.couponType,
          beSharedMinPrice: beSharedCoupon.minPrice || undefined,
          beSharedCouponDiscount: beSharedCoupon.couponDiscount || undefined,
          beSharedVerificationType: beSharedCoupon.verificationType ? 1 : 0,
          beSharedCouponTotal: beSharedCoupon.couponTotal,
        });
      }
    });
  };
  const addSplitCouponSubmit = () => {
    const { getForm: getBaseInfoForm } = baseInfoRef.current;
    const { getForm: getShareCouponForm } = shareCouponRef.current;
    const { getForm: getSharedCouponForm } = sharedCouponRef.current;
    Promise.all([
      getBaseInfoForm().validateFields(),
      getShareCouponForm().validateFields(),
      getSharedCouponForm().validateFields(),
    ])
      .then((values) => {
        values[1].useStartTime = `${dayJs(values[1].time[0]).format(
          "YYYY-MM-DD"
        )} 00:00:00`;
        values[1].useEndTime = `${dayJs(values[1].time[1]).format(
          "YYYY-MM-DD"
        )} 23:59:59`;
        values[1].primaryKey = values[1].primaryKey.join(",");
        values[2].beSharedPrimaryKey = values[2].beSharedPrimaryKey.join(",");
        delete values[1].time;
        CouponManageAPI.saveActivity({
          ...values[0],
          ...values[1],
          ...values[2],
        }).then(({ code, message: msg }) => {
          if (code === "200") {
            message.success("新增成功");
            getBaseInfoForm().resetFields();
            getShareCouponForm().resetFields();
            getSharedCouponForm().resetFields();
            backRoute();
          } else {
            message.error(msg);
          }
        });
      })
      .catch((error) => {
        message.error(error.errorFields[0].errors[0]);
      });
  };
  //  返回
  const backRoute = () => {
    history(-1);
  };

  useEffect(() => {
    getMakeList();
    if (props.location) {
        const { id: splitCouponId }: any = qs.parse(props.location.search);
      setSplitCouponId(splitCouponId);
      if (splitCouponId) {
        getSplitCouponDetail(splitCouponId);
      }
    }
  }, []);

  return (
    <div className="add-or-edit-or-detail-wrap">
      <div className="add-or-edit-or-detail">
        {/*  基本信息 */}
        <BaseInfo ref={baseInfoRef} isDetail={!!splitCouponId} />
        {/*  分享者优惠券 */}
        <ShareCouponInfo
          ref={shareCouponRef}
          makeList={makeList}
          isDetail={!!splitCouponId}
        />
        {/*  被分享者优惠券 */}
        <SharedCouponInfo
          ref={sharedCouponRef}
          makeList={makeList}
          shareCouponRef={shareCouponRef}
          isDetail={!!splitCouponId}
        />
      </div>
      <div className="footer-operate">
        <Button onClick={backRoute}>返回</Button>
        {!splitCouponId && (
          <Button type="primary" onClick={addSplitCouponSubmit}>
            确定
          </Button>
        )}
      </div>
    </div>
  );
};

export default SplitCouponOperate;
