import React, { useEffect, useState } from 'react';
import qs from 'query-string';
import { useNavigate } from 'react-router-dom';
import {
  Button,
  Checkbox,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Radio,
  RadioChangeEvent,
  Select,
  Space,
  Upload,
  UploadProps,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import saveAs from 'file-saver';
import { isNull } from 'lodash';
import { TableDetailView } from '~/components/tableDetailView';
import { CommonAPI, CouponManageAPI, MakeManageAPI } from '~/api';
import { CouponPageListType } from '~/api/interface/couponManage';
import { maxLength, maxLength6, maxLength8, maxNumber } from '~/utils/validateUtils';
import { Uploader } from '~/components/uploader';

// 列表的类型
type DetailType = (ReturnType<CouponPageListType> extends Promise<infer T>
  ? T
  : never)['result']['list'][0];

export default function CouponDetail(props: { location: { search: string } }) {
  // 参数解析
  const option: any = qs.parse(props.location.search);
  // 路由钩子
  const history: any = useNavigate();
  // 表单钩子
  const [form] = Form.useForm();
  // 当前是否能编辑
  const [editDisable, setEditDisable] = useState(false);
  // 有效期类型
  const [isFixedTime, setIsFixedTime] = useState(0);
  // 优惠券类型
  const [couponType, setCouponType] = useState(1);
  // 打折条件
  const [discountRule, setDiscountRule] = useState(1);
  // 发放方式
  const [getType, setGetType] = useState(1);
  // 最多优惠
  const [maxDiscount, setMaxDiscount] = useState(false);
  // 是否限量
  const [isLimited, setIsLimited] = useState(true);
  // 优惠券数据
  const [couponDetail, setCouponDetail] = useState<DetailType>();
  // 品牌列表
  const [primaryOptions, setPrimaryOptions] = useState<{ label: string; value: number }[]>();
  // 获取优惠券详情
  const getCouponDetail = async ({ id, type }: { id: string; type: number }) => {
    const res = await CouponManageAPI.CouponPageList({
      couponId: id,
      useType: type,
      pageNo: 1,
      pageSize: 1,
    });
    if (res && res.code === '200') {
      const data = res.result.list[0];
      // 优惠券详情
      setCouponDetail(data);
      // 回显表单
      form.setFieldsValue({
        ...data,
        rangeTime: [dayjs(data.useStartTime), dayjs(data.useEndTime)],
        // useStartTime: data.useStartTime && dayjs(data.useStartTime),
        // useEndTime: data.useEndTime && dayjs(data.useEndTime),
        primaryKey: data.primaryKey?.split(',')?.map((i) => Number(i)),
      });
      // 设置有效期类型
      setIsFixedTime(data.isFixedTime);
      // 设置券类型
      setCouponType(data.couponType);
      // 当券为有最低消费且为打折券时，设置打折券的类型
      if (data.couponType === 1 && !isNull(data.minPrice)) {
        setDiscountRule(2);
      } else {
        setDiscountRule(1);
      }
      // 设置发放方式
      setGetType(data.getType);
      // 回显最多优惠
      if (data.preferentialLimit) {
        setMaxDiscount(true);
      }
      // console.log("getCouponDetail --->", data.preferentialLimit);
    }
  };
  // 获取品牌列表
  const getListBrandInfo = async () => {
    const res = await MakeManageAPI.getListBrandInfo({
      pageNo: 1,
      pageSize: 9999,
    });
    setPrimaryOptions(
      res.result?.list?.map((i) => {
        return { label: i.brandName, value: i.id };
      }),
    );
  };
  // 有效期状态
  const handleFixedTime = ({ target: { value } }: RadioChangeEvent) => {
    setIsFixedTime(value);
  };
  // 优惠券类型
  const handleCouponType = ({ target: { value } }: RadioChangeEvent) => {
    // 切换时候清除已填数据（未考虑编辑情况）
    form.setFieldsValue({
      minPrice: undefined,
      couponDiscount: undefined,
      preferentialLimit: undefined,
      couponMoney: undefined,
    });
    setCouponType(value);
  };
  // 打折条件
  const handleDiscountRule = ({ target: { value } }: RadioChangeEvent) => {
    setDiscountRule(value);
  };
  // 最多优惠
  const handleMaxDiscount = ({ target: { checked } }: CheckboxChangeEvent) => {
    setMaxDiscount(checked);
  };
  // 发放方式
  const handleGetType = ({ target: { value } }: RadioChangeEvent) => {
    setGetType(value);
  };
  // 是否限量
  const handleIsLimited = ({ target: { value } }: RadioChangeEvent) => {
    setIsLimited(value);
    if (!value) {
      form.setFieldValue('couponTotal', '0');
    } else {
      form.setFieldValue('couponTotal', undefined);
    }
  };
  // 校验数据
  const handleOk = () => {
    if (editDisable) {
      return history(-1);
    }
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit({
          ...values,
          // couponDiscount: Number(values.couponDiscount),
          primaryKey: values.primaryKey.join(','),
          useStartTime:
            values.rangeTime && dayjs(values.rangeTime[0]).format('YYYY-MM-DD 00:00:00'),
          useEndTime: values.rangeTime && dayjs(values.rangeTime[1]).format('YYYY-MM-DD 23:59:59'),
          useType: option.type,
        });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (data: DetailType) => {
    // console.log("handleSubmit --->", data);
    const formData = new FormData();
    const blob = new Blob([JSON.stringify(data)], {
      type: 'application/json',
    });
    formData.append('couponInfoVO', blob);
    formData.append('file', data.file);
    const res = await CouponManageAPI.CouponSave(formData);
    if (res && res.code === '200') {
      message.success('操作成功', 1).then(() => history(-1));
    } else {
      message.error(res.message);
    }
  };

  // 组件加载
  useEffect(() => {
    // 获取品牌列表
    getListBrandInfo().then();
    if (!option.id) return;
    // 获取回显数据
    getCouponDetail(option).then();
    // 设置是否可以编辑
    setEditDisable(true);
  }, []);
  return (
    <>
      <TableDetailView
        isBack
        isFooter
        onCancel={() => {
          history(-1);
        }}
        onOK={handleOk}
      >
        <div className='detail-form'>
          <Form
            name='addForm'
            form={form}
            labelAlign='right'
            disabled={editDisable}
            // labelCol={{ span: 3 }}
          >
            <div className='detail-label'>基本信息</div>
            <Form.Item
              label='优惠券名称'
              name='couponName'
              rules={[{ required: true, message: '请输入优惠券名称' }]}
            >
              <Input placeholder='请输入优惠券名称' maxLength={10} allowClear showCount />
            </Form.Item>
            <Form.Item
              name='isFixedTime'
              label='有效期'
              rules={[{ required: true, message: '请选择有效期' }]}
              initialValue={0}
            >
              <Radio.Group
                style={{ marginTop: '2px' }}
                options={[
                  { value: 0, label: '起始日期 至 结束日期' },
                  { value: 1, label: '领取当日起' },
                  { value: 2, label: '领取次日起' },
                ]}
                value={isFixedTime}
                onChange={handleFixedTime}
              />
            </Form.Item>
            {isFixedTime === 0 && (
              <Form.Item
                label={' '}
                colon={false}
                name='rangeTime'
                rules={[{ required: true, message: '请输入有效期' }]}
                required
                style={{
                  width: '400px',
                  marginLeft: '55px',
                }}
              >
                <DatePicker.RangePicker
                  format='YYYY-MM-DD'
                  disabledDate={(current) => {
                    // 限制时间不可早于昨日
                    return current && current < dayjs().subtract(1, 'days');
                  }}
                />
              </Form.Item>
            )}
            {isFixedTime === 1 && (
              <Form.Item
                label={' '}
                colon={false}
                name='couponDay'
                rules={[{ required: true, message: '请输入有效期' }]}
                style={{ width: '200px', marginLeft: '55px' }}
              >
                <Input
                  placeholder='请输入天数'
                  allowClear
                  suffix='天内可用'
                  type='number'
                  onInput={maxLength}
                />
              </Form.Item>
            )}
            {isFixedTime === 2 && (
              <Form.Item
                label={' '}
                colon={false}
                name='couponDay'
                rules={[{ required: true, message: '请输入有效期' }]}
                style={{ width: '200px', marginLeft: '55px' }}
              >
                <Input
                  placeholder='请输入天数'
                  maxLength={10}
                  allowClear
                  suffix='天内可用'
                  type='number'
                  onInput={maxLength}
                />
              </Form.Item>
            )}
            <Form.Item
              name='primaryKey'
              label='品牌范围'
              rules={[{ required: true, message: '请选择品牌范围' }]}
            >
              <Select
                mode='multiple'
                placeholder='请选择品牌范围'
                maxLength={50}
                allowClear
                options={primaryOptions}
              />
            </Form.Item>
            {/* <div className="detail-form-tips"> */}
            {/*  说明：一张优惠券最多可以选择50个指定品牌。优惠券一旦创建，指定品牌只能增加，不能删除。 */}
            {/* </div> */}
            <Form.Item
              label='发放方式'
              name='getType'
              rules={[{ required: true, message: '请选择发放方式' }]}
              initialValue={1}
            >
              <Radio.Group
                style={{ marginTop: '4px' }}
                options={[
                  { label: '主动领取', value: 1 },
                  { label: '系统发放', value: 2 },
                  { label: '批量导入用户', value: 3 },
                  { label: '活动裂变券', value: 4, disabled: true },
                ]}
                value={getType}
                onChange={handleGetType}
              />
            </Form.Item>
            {getType === 2 && (
              <Form.Item
                name='userTag'
                label='用户标签'
                rules={[{ required: true, message: '请选择用户标签' }]}
              >
                <Select
                  placeholder='请选择用户标签'
                  allowClear
                  maxLength={50}
                  options={[
                    { label: '新用户', value: 1 },
                    { label: '实名认证', value: 2 },
                    { label: '企业认证', value: 3 },
                  ]}
                />
              </Form.Item>
            )}
            {getType === 3 && (
              <>
                <Form.Item
                  name='fileUrl'
                  label='文件地址'
                  rules={[{ required: true, message: '请上传文件' }]}
                  wrapperCol={{ span: 6 }}
                  hidden
                >
                  <Input placeholder='请上传文件' />
                </Form.Item>
                <Form.Item
                  name='file'
                  label='上传模板'
                  rules={[{ required: true, message: '请上传模板' }]}
                >
                  <Uploader
                    listType='text'
                    fileType={[
                      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                      'application/vnd.ms-excel',
                    ]}
                    fileUpload={false}
                    onChange={(file) => {
                      // 上传到服务器
                      const formData = new FormData();
                      formData.append('uploadFile', file[0]);
                      CommonAPI.fileUpload(formData).then((res: any) => {
                        if (res && res.code === '200') {
                          form.setFieldValue('fileUrl', res?.result?.filePath);
                          form.setFieldValue('file', file[0]);
                        } else {
                          message.error('文件上传失败').then();
                        }
                      });
                    }}
                    // 默认文件列表
                    defaultFileList={
                      couponDetail?.fileUrl
                        ? [{ url: couponDetail?.file, name: '用户数据.xlsx' }]
                        : []
                    }
                  >
                    <Button icon={<UploadOutlined />}>上传文件</Button>
                  </Uploader>
                  <Button
                    type='link'
                    onClick={() => {
                      // 使用file-save保存文件，文件链接为：https://share-fly.oss-cn-hangzhou.aliyuncs.com/doc/coupon-template.xlsx
                      saveAs(
                        'https://share-fly.oss-cn-hangzhou.aliyuncs.com/doc/coupon-template.xlsx',
                        '导入模板.xlsx',
                      );
                    }}
                    style={{ position: 'absolute', top: '0px', right: '120px' }}
                  >
                    模板下载
                  </Button>
                </Form.Item>
              </>
            )}
            <div className='detail-label'>面额信息</div>
            <Form.Item
              label='优惠类型'
              name='couponType'
              rules={[{ required: true, message: '请选择优惠类型' }]}
              initialValue={1}
            >
              <Radio.Group
                style={{ marginTop: '4px' }}
                options={[
                  { label: '折扣券', value: 1 },
                  { label: '满减券', value: 2 },
                  { label: '无门槛', value: 3 },
                ]}
                value={couponType}
                onChange={handleCouponType}
              />
            </Form.Item>
            {couponType === 1 && (
              <>
                <Form.Item label='打折条件' rules={[{ required: true, message: '请选择打折条件' }]}>
                  <Radio.Group
                    style={{ marginTop: '4px' }}
                    options={[
                      { label: '无门槛', value: 1 },
                      { label: '有门槛', value: 2 },
                    ]}
                    value={discountRule}
                    onChange={handleDiscountRule}
                  />
                </Form.Item>
                {discountRule === 2 && (
                  <Form.Item
                    name='minPrice'
                    label='订单满'
                    rules={[{ required: true, message: '请输入金额' }]}
                    wrapperCol={{ span: 6 }}
                  >
                    <Input
                      placeholder='请输入金额'
                      suffix='元'
                      type='number'
                      onInput={maxLength8}
                    />
                  </Form.Item>
                )}
                <Form.Item
                  name='couponDiscount'
                  label='打'
                  rules={[
                    { required: true, message: '请输入数字' },
                    {
                      pattern: /^10(\.00)?$|^(\d|[1-9])(\.\d{1,2})?$/,
                      message: '只能输入0.01到10.00的两位小数',
                    },
                  ]}
                  wrapperCol={{ span: 6 }}
                >
                  <Input
                    placeholder='请输入数字'
                    suffix='折'
                    type='number'
                    // onInput={onlyNumber}
                  />
                </Form.Item>
                <Checkbox
                  onChange={handleMaxDiscount}
                  style={{ marginTop: '6px', marginRight: '10px' }}
                  checked={maxDiscount}
                />
                <Form.Item
                  name='preferentialLimit'
                  label='最多优惠'
                  rules={[{ required: maxDiscount, message: '请输入金额' }]}
                  wrapperCol={{ span: 7 }}
                  style={{ display: 'inline-block', width: '85%' }}
                >
                  <Input placeholder='请输入金额' suffix='元' type='number' onInput={maxLength8} />
                </Form.Item>
                <div className='detail-form-tips'>说明：最多优惠金额不可高于满折后的价格。</div>
              </>
            )}
            {couponType === 2 && (
              <>
                <Form.Item style={{ marginLeft: '30px' }}>
                  <Form.Item
                    name='minPrice'
                    label='满'
                    colon={false}
                    rules={[{ required: true, message: '请输入金额' }]}
                    style={{
                      display: 'inline-block',
                      width: 'calc(40% - 8px)',
                    }}
                  >
                    <Input
                      placeholder='请输入金额'
                      suffix='元'
                      type='number'
                      onInput={maxLength8}
                      onChange={() => {
                        form.validateFields(['couponMoney']).then();
                      }}
                    />
                  </Form.Item>
                  <Form.Item
                    name='couponMoney'
                    label='减'
                    colon={false}
                    rules={[
                      { required: true, message: '请输入金额' },
                      // 满减金额不能大于原价
                      {
                        validator: (_, value) =>
                          Number(value) > Number(form.getFieldValue('minPrice'))
                            ? Promise.reject('满减金额不能大于原价')
                            : Promise.resolve(),
                      },
                    ]}
                    style={{
                      display: 'inline-block',
                      width: 'calc(40% - 8px)',
                      margin: '0 8px',
                    }}
                  >
                    <Input
                      placeholder='请输入金额'
                      suffix='元'
                      type='number'
                      onInput={maxLength8}
                    />
                  </Form.Item>
                </Form.Item>
              </>
            )}
            {couponType === 3 && (
              <>
                <Form.Item
                  name='couponMoney'
                  label='券的面额'
                  rules={[
                    { required: true, message: '请输入面额' },
                    {
                      validator: (_, value) =>
                        Number(value) > 200000
                          ? Promise.reject('面额不得超过20万元')
                          : Promise.resolve(),
                    },
                  ]}
                  wrapperCol={{ span: 6 }}
                >
                  <Input placeholder='请输入面额' suffix='元' type='number' onInput={maxLength6} />
                </Form.Item>
                <div className='detail-form-tips'>说明：请输入整数金额，面额不得超过20万元。</div>
                <Form.Item
                  label='核销方式'
                  name='verificationType'
                  rules={[{ required: true, message: '请选择核销方式' }]}
                >
                  <Radio.Group
                    style={{ marginTop: '4px' }}
                    options={[
                      { label: '单次核销', value: false },
                      { label: '多次核销', value: true },
                    ]}
                  />
                </Form.Item>
              </>
            )}
            <Form.Item
              label='是否限量'
              name='isLimited'
              rules={[{ required: true, message: '请选择核销方式' }]}
              initialValue
              hidden
            >
              <Radio.Group
                style={{ marginTop: '4px' }}
                options={[
                  { label: '限量', value: true },
                  { label: '不限量', value: false },
                ]}
                value={isLimited}
                onChange={handleIsLimited}
              />
            </Form.Item>
            <Form.Item
              name='couponTotal'
              label='发行量'
              rules={[
                { required: true, message: '请输入发行量' },
                { max: 100000, message: '最大不能超过100000' },
              ]}
              hidden={!isLimited}
            >
              <Input
                placeholder='至少1张，不超过10万'
                suffix='张'
                type='number'
                onInput={maxNumber}
              />
            </Form.Item>
            <div className='detail-form-tips' style={{ color: 'red' }}>
              说明：优惠券创建后，发行量只能增加不能减少，请谨慎设置。
            </div>
            <Form.Item
              name='restrictedAccess'
              label='每人限领'
              rules={[{ required: true, message: '请选择限领张数' }]}
            >
              <Select
                placeholder='至少1张，不超过10万'
                options={[
                  { label: '1张', value: 1 },
                  { label: '2张', value: 2 },
                  { label: '3张', value: 3 },
                  { label: '4张', value: 4 },
                  { label: '5张', value: 5 },
                  // { label: "不限", value: 0 },
                ]}
                // onChange={(e) => {
                //   if (e === 0) {
                //     form.setFieldsValue({ isLimited: false });
                //   } else {
                //     form.setFieldsValue({ isLimited: true });
                //   }
                // }}
              />
            </Form.Item>
          </Form>
        </div>
      </TableDetailView>
    </>
  );
}
