import React, { useState, useEffect } from "react";
import { Form, Input, InputNumber, Select, Divider, Radio, Row, Image, Modal, Button } from "antd";
import { formItemLayout } from "../entity";
import { FormInstance } from "antd/lib/form";
import * as api from "../api";
import WareLimitType from "./WareLimitType";
import ShopLimit from "./ShopLimit";
import useInitail from "@/hooks/useInitail";
import { PaymentTypeEnum } from '@/pages/coupon/CashChange/api';
import { RightOutlined } from '@ant-design/icons';
import RenderSelectGoos from '@/pages/capital/ReceiveRules/subPages/GoodsDimension/components/RenderSelectGoos';

const Option = Select.Option;
interface Props {
  // brandId: number,
  info: MktConponSpace.ConListParams;
  form: FormInstance;
  readonly: boolean;
  getCouponType?: Function;
  confNo?: string;
  limitCoupon?: string[]; // 优惠券类型限制
  carSelectApi?: Function
  expires?: boolean;
  changeEditKeys?: string[];
}

export default function FullReduce({
  info,
  readonly,
  form,
  getCouponType,
  confNo,
  limitCoupon,
  carSelectApi,
  expires,
  changeEditKeys,
}: Props) {
  const [classifyInfo, setClassifyInfo] = useState({ code: "" });
  const { data: ClassifyList } = useInitail(api.fetchClassifyList, [], {});
  const { data: cashChangeTypes } = useInitail(api.fetchExchangeList, [], {});
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    setClassifyInfo({ code: info.classifyCode });
    const currentItem = ClassifyList.filter(
      (i) => i.code === info.classifyCode
    );
    if (currentItem.length) {
      getCouponType && getCouponType(currentItem[0].type);
    }
  }, [info.classifyCode]);

  function changeScene(v: any) {
    const currentItems = ClassifyList.filter((i) => i.code === v.value)[0];
    form.setFieldsValue({
      aliasName: currentItems.type == 1 ? currentItems.name : undefined,
      settlementType: 1,
      settlementCalType: v.value === "xjdhq" ? 1 : undefined,
    });
    getCouponType && getCouponType(currentItems.type);
    setClassifyInfo({ code: v.value });
    let limitItem = currentItems.schemes
      .split(",")
      .map((i: string) => {
        if (i === "1") {
          return ({
            externalRely: true,
            limitScheme: true,
            schemeType: i
          });
        } else { return ({ schemeType: i, limitScheme: false }); }
      });
    if (currentItems.schemes.split(",").includes('7')) {
      const item = limitItem[1];
      limitItem[1] = limitItem[2];
      limitItem[2] = item;
    }
    // form.setFieldsValue({ schemeList: currentItems.schemes !== "0" ? limitItem : [] });
    form.setFieldsValue({ schemeList: limitItem });
  }

  // 优惠券类型限制
  function screenCouponType() {
    const list = limitCoupon && limitCoupon.length ? ClassifyList.filter(v => limitCoupon.includes(v.code)) : ClassifyList;
    return list || [];
  }

  return (
    <div>
      <Form form={form} {...formItemLayout}>
        <Form.Item
          label="优惠券类型"
          name="classifyCode"
          rules={[{ required: true, message: "请选择优惠券类型" }]}
        >
          <Select
            optionFilterProp="children"
            showSearch
            disabled={readonly || !!confNo}
            labelInValue
            placeholder="请选择优惠券类型"
            style={{ width: "100%" }}
            onChange={(value, option) => changeScene(option)}
          >
            {screenCouponType().map((item) => (
              <Option key={item.code} value={item.code}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        {classifyInfo.code === "xjdhq" && (
          <Form.Item
            label="现金兑换券类型"
            name="exchangeTypeId"
            rules={[{ required: true, message: "请选择优惠券类型" }]}
          >
            <Select
              optionFilterProp="children"
              showSearch
              disabled={readonly || !!confNo}
              labelInValue
              placeholder="请选择兑换券类型"
              style={{ width: "100%" }}
            >
              {cashChangeTypes.map((item) => (
                <Option key={item.id} value={item.id}>
                  {`${item.name} [${PaymentTypeEnum[item.paymentType]}]`}
                </Option>
              ))}
            </Select>
          </Form.Item>
        )}
        <Form.Item
          label="优惠券别名"
          name="aliasName"
          rules={[{ required: true, message: "请输入优惠券名称" }]}
          extra={
            <Row style={{ marginTop: 10 }}>
              <span style={{ color: 'red', fontSize: 12 }}>示例：至高6500元鲸喜基金；</span>
              <div
                style={{ color: '#4189FD', fontSize: 12 }}
                onClick={() => setVisible(true)}
              >
                预览<RightOutlined />
              </div>
            </Row>
          }
        >
          <Input
            disabled={changeEditKeys ? !changeEditKeys.includes("aliasName") : (readonly || !!confNo)}
            placeholder="请输入优惠券名称"
            maxLength={20}
          />
        </Form.Item>

        {!!expires && (
          <Form.Item
            label="优惠券有效期"
            name="expires"
            extra={<span style={{ fontSize: 12, color: '#999' }}>固定天数为0的时候，即有效期为当天23：59：59</span>}
            rules={[{ required: true, message: "请输入优惠券固定天数有效期时间" }]}
          >
            <InputNumber
              disabled={readonly || !!confNo}
              style={{ width: "100%" }}
              placeholder="请输入"
              addonAfter="天"
              precision={0}
              min={0}
            />
          </Form.Item>
        )}
        {/* 实物兑换券选择兑换物品 */}
        {classifyInfo.code === "dhyhq" && (
          <Form.Item label="兑换物品" name="amsCode" extra={<span style={{ fontSize: 12 }}>*兑换物品仅限一个</span>} rules={[{ required: true, message: '请选择' }]}>
            <RenderSelectGoos multiple={false} disabled={readonly} />
          </Form.Item>
        )}
        <Form.Item
          label="优惠券券面金额"
          name="amount"
          rules={[{ required: true, message: "请输入优惠券销售价格" }]}
        >
          <InputNumber
            disabled={readonly || !!confNo}
            style={{ width: "100%" }}
            placeholder="请输入"
          />
        </Form.Item>
        <Form.Item
          label="结算方式"
          name="settlementType"
          rules={[{ required: true, message: "请选择结算方式" }]}
        >
          <Radio.Group disabled={readonly}>
            <Radio key={1} value={1}>
              商家结算给三方
            </Radio>
            {!["dhyhq"].includes(classifyInfo.code) && (
              <Radio key={2} value={2}>
                厂家结算给商家
              </Radio>
            )}
          </Radio.Group>
        </Form.Item>

        <Form.Item
          label="结算金额计算方式"
          name="settlementCalType"
          rules={[{ required: true, message: "请输入金额" }]}
        >
          <Radio.Group disabled={readonly}>
            <Radio key={1} value={1}>
              系数
            </Radio>
            {!["xjdhq"].includes(classifyInfo.code) && (
              <Radio key={2} value={2}>
                金额
              </Radio>
            )}
          </Radio.Group>
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.settlementCalType != currentValues.settlementCalType}
        >
          {({ getFieldValue }): any => {
            const calType = getFieldValue("settlementCalType");
            const max = calType == 1 ? 1 : undefined;
            return (
              <Form.Item
                label={calType == 1 ? "结算系数" : "结算金额(元)"}
                name="settlementCalValue"
                rules={[
                  { required: true, message: "请输入" },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (calType === 2 && value > getFieldValue("amount")) {
                        return Promise.reject(
                          new Error("结算金额不能大于优惠券券面金额")
                        );
                      }
                      return Promise.resolve();
                    },
                  }),
                ]}
              >
                <InputNumber
                  style={{ width: "100%" }}
                  disabled={readonly}
                  placeholder="请输入"
                  min={0}
                  max={max}
                  precision={2}
                />
              </Form.Item>
            );
          }}
        </Form.Item>
        <ShopLimit
          form={form}
          readonly={readonly}
          formItemLayout={formItemLayout}
        />
        <Divider orientation="center">场景限制条件</Divider>
        <WareLimitType
          readonly={readonly}
          info={info}
          form={form}
          formItemLayout={formItemLayout}
          schemes={classifyInfo}
          carSelectApi={carSelectApi}
          changeEditKeys={changeEditKeys}
        />
      </Form>
      <Modal
        visible={visible}
        centered
        onCancel={() => setVisible(false)}
        footer={false}
      >
        <Image
          width={300}
          src="https://feewee-1255997270.cos.ap-chengdu.myqcloud.com/static/mkt/coupon/aliasName/example?"
        />
      </Modal>
    </div>
  );
}
