import BaseIndex from '@/components/Base/BaseIndex';
import BaseModel from '@/components/Base/BaseModel';
import BaseTable from '@/components/Base/BaseTable';
import {
  _getAdvertiseInfo,
  _getCoupon,
  _getCouponSelection,
  _getPenalty,
  _getPriceEvent,
  _postCoupon,
  _putPenalty,
} from '@/services/setting';
import Helper from '@/util/searchHelper';
import { EditOutlined, PlusSquareOutlined, UndoOutlined } from '@ant-design/icons';

import BaseSearch from '@/components/Base/BaseSearch';
import {
  ActionType,
  ProCard,
  ProForm,
  ProFormCheckbox,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, message, Tag } from 'antd';
import { FormInstance } from 'antd/lib';
import { useEffect, useRef, useState } from 'react';
import { AdvertiseColumns, PriceEventColumns } from './columns';
import { CreateModal } from './PriceEventForm';
export type EnumCouponCondition = {
  LimitByOrderAmount: boolean;
  MinOrderAmount: boolean;
  CanCombine: boolean;
  OneCouponPerOrder: boolean;
  isRefundableRemain: boolean;
};
export default function Index() {
  /**********************************狀態管理**********************************/
  const [tab, setTab] = useState('tab1');
  const [searchKey, setSearchKey] = useState('');
  const [couponTypeOptions, setCouponTypeOptions] = useState([]);
  const [conditionOptions, setConditionOptions] = useState([]);
  const [discountUnitOptions, setDiscountUnitOptions] = useState([]);
  const actionRef = useRef<ActionType>();
  const advertiseActionRef = useRef<ActionType>();
  const getCouponSelection = async () => {
    const response = await _getCouponSelection();
    setCouponTypeOptions(response.data.coupon_type);
    setConditionOptions(response.data.condition_desc);
    setDiscountUnitOptions(response.data.discount_unit);
  };
  const [penaltyFormReadOnly, setPenaltyFormReadOnly] = useState(true);
  const [penaltyData, setPenaltyData] = useState<undefined>();
  const penaltyRef = useRef<FormInstance>();
  const getPenalty = async () => {
    const response = await _getPenalty();
    setPenaltyData(response.data[0]);
  };

  useEffect(() => {
    getCouponSelection();
    getPenalty();
  }, []);
  /**********************************狀態管理**********************************/

  /**********************************組件初始化**********************************/
  // const uploadProps: UploadProps = {
  //   name: "file",
  //   showUploadList: false, // 不显示上传列表
  //   beforeUpload: () => false, // 阻止自动上传
  //   accept: "video/*",
  //   onChange: async (info) => {
  //     const file = info.fileList[0]?.originFileObj;
  //     if (file) {
  //       // 验证是否为图片
  //       if (!file.type.startsWith("video/")) {
  //         message.error("请上传视频文件");
  //         return;
  //       }
  //       const maxSize = 100 * 1024 * 1024; // 100MB
  //       if (file.size > maxSize) {
  //         message.error("视频文件不能超过 100MB");
  //         return;
  //       }

  //       try {
  //         setLoading(true);
  //         const response = await _updateBannerVideo({
  //           youtube_url: file,
  //         });
  //         if (response.status) {
  //           message.success("上传成功");
  //           BannerFormDataRefresh();
  //         } else {
  //           message.error("上传失败");
  //         }
  //       } catch (error) {
  //         message.error("上传失败");
  //         console.error(error);
  //       } finally {
  //         setLoading(false);
  //       }
  //     }
  //   },
  // };
  const CouponCard = () => {
    return (
      <div>
        <BaseTable<API.CouponData>
          searchKey={searchKey}
          props={{
            headerTitle: '優惠券列表',
            actionRef: actionRef,
            optionsRender(props, defaultDom) {
              const createCoupon = (
                <BaseModel
                  allowUpdate={false}
                  readOnly={false}
                  modalFormProps={{
                    onFinish: async (values) => {
                      const condition: EnumCouponCondition = {
                        LimitByOrderAmount: false,
                        MinOrderAmount: false,
                        CanCombine: false,
                        OneCouponPerOrder: false,
                        isRefundableRemain: false,
                      };
                      if (values.condition) {
                        values.condition.map((item: string) => {
                          condition[item as keyof EnumCouponCondition] = true;
                          return item;
                        });
                      }
                      values.condition = condition;
                      console.log(values);

                      try {
                        await _postCoupon(values as any);
                        message.success('創建優惠券成功');
                      } catch (error) {
                        message.error('創建優惠券失敗');
                      } finally {
                        actionRef.current?.reload();
                      }
                      return true;
                    },
                    grid: true,
                    trigger: <Button icon={<PlusSquareOutlined />} type="text" />,
                    submitter: {
                      searchConfig: {
                        resetText: '取消',
                        submitText: '確認',
                      },
                    },
                  }}
                  title="新增優惠券"
                >
                  <ProFormText
                    colProps={{ span: 12 }}
                    label="優惠券名稱"
                    name="name"
                    rules={[{ required: true }]}
                  />
                  <ProFormDigit
                    colProps={{ span: 12 }}
                    label="優惠金額"
                    name="amount"
                    rules={[{ required: true }]}
                    min={0}
                  />
                  <ProFormSelect
                    colProps={{ span: 12 }}
                    label="折扣方式"
                    name="unit"
                    rules={[{ required: true }]}
                    options={discountUnitOptions.map((item) => ({
                      label: item,
                      value: item,
                    }))}
                  />
                  <ProFormSelect
                    colProps={{ span: 12 }}
                    label="優惠券類型"
                    name="coupon_type"
                    rules={[{ required: true }]}
                    options={couponTypeOptions.map((item) => ({
                      label: item,
                      value: item,
                    }))}
                  />
                  <ProFormDigit
                    colProps={{ span: 12 }}
                    label="最低消費金額"
                    name="min_purchase_amount"
                    rules={[{ required: true }]}
                    min={0}
                  />
                  <ProFormDigit
                    colProps={{ span: 12 }}
                    label="有效期限(天)"
                    name="valid_date"
                    rules={[{ required: true }]}
                    min={1}
                  />
                  <ProFormTextArea
                    colProps={{ span: 24 }}
                    label="優惠券描述"
                    name="description"
                    rules={[{ required: true }]}
                  />
                  <ProFormCheckbox.Group
                    colProps={{ span: 24 }}
                    label="使用條件"
                    name={['condition']}
                    options={Object.entries(conditionOptions).map(([key, value]) => ({
                      label: value,
                      value: key,
                    }))}
                  />
                </BaseModel>
              );
              return [createCoupon, ...defaultDom];
            },
            columns: [
              {
                title: '優惠券名稱',
                dataIndex: 'name',
                width: 150,
                ellipsis: true,
              },
              {
                title: '優惠金額',
                dataIndex: 'amount',
                width: 100,
                render: (amount, record) => `${record.unit}${amount}`,
              },
              {
                title: '優惠券類型',
                dataIndex: 'coupon_type',
                width: 120,
              },
              {
                title: '優惠券代碼',
                dataIndex: 'redeem_code',
                width: 150,
                copyable: true,
                ellipsis: {
                  showTitle: true,
                },
                onCell: () => ({
                  style: {
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    maxWidth: 100,
                  },
                }),
              },
              {
                title: '最低消費金額',
                dataIndex: 'min_purchase_amount',
                width: 120,
                render: (amount, record) => `${record.unit}${amount}`,
              },
              {
                title: '有效期限',
                dataIndex: 'valid_date',
                width: 100,
                render: (days) => `${days}天`,
              },
              {
                title: '使用條件',
                dataIndex: 'condition',
                width: 200,
                render: (condition) => (
                  <div>
                    {(condition as any)?.CanCombine && <Tag color="blue">可疊加</Tag>}
                    {(condition as any)?.MinOrderAmount && <Tag color="green">最低消費</Tag>}
                    {(condition as any)?.OneCouponPerOrder && <Tag color="orange">單筆限用</Tag>}
                    {(condition as any)?.LimitByOrderAmount && <Tag color="purple">金額限制</Tag>}
                    {(condition as any)?.isRefundableRemain && <Tag color="cyan">可退餘額</Tag>}
                  </div>
                ),
              },
              {
                title: '描述',
                dataIndex: 'description',
                width: 300,
                ellipsis: true,
              },
            ],
            request: async () => {
              const dataSource = await _getCoupon();
              if (searchKey) {
                return {
                  success: true,
                  data: Helper<API.CouponData>({
                    dataSource: dataSource.data,
                    keyWord: searchKey,
                  }),
                };
              }
              return {
                success: true,
                data: dataSource.data,
              };
            },
          }}
        />
      </div>
    );
  };
  const PriceEventTable = () => {
    const actionRef = useRef<ActionType>();

    return (
      <>
        <BaseTable<API.PriceEvent>
          props={{
            scroll: { x: 2000 },
            headerTitle: '時段價格設置',
            actionRef,
            columns: PriceEventColumns({
              mainTableReload: () => actionRef.current?.reload(),
            }),
            request: async () => {
              const response = await _getPriceEvent();
              return {
                data: response.data,
                success: true,
              };
            },
            // toolBarRender: () => [
            //   <CreateModal
            //     key="add"
            //     initData={currentRecord}
            //     mainTableReload={() => actionRef.current?.reload()}
            //   />,
            // ],
          }}
        />
      </>
    );
  };

  const PenaltyCard = () => {
    return (
      <>
        <ProForm
          formRef={penaltyRef}
          onFinish={async (values) => {
            console.log(values);
            try {
              await _putPenalty(values as any);
              message.success('修改成功');
            } catch (error) {
              message.error('修改失敗');
            } finally {
              setPenaltyFormReadOnly(true);
              await getPenalty();
            }
          }}
          grid={true}
          onInit={() => {
            penaltyRef.current?.setFieldsValue(penaltyData);
          }}
          readonly={penaltyFormReadOnly}
          submitter={{
            render: (_, dom) => {
              return penaltyFormReadOnly ? (
                <Button
                  type="primary"
                  icon={<EditOutlined />}
                  onClick={() => setPenaltyFormReadOnly(false)}
                />
              ) : (
                [
                  ...dom,
                  <Button
                    type="primary"
                    icon={<UndoOutlined />}
                    key="undo"
                    onClick={() => {
                      setPenaltyFormReadOnly(true);
                      penaltyRef.current?.setFieldsValue(penaltyData);
                    }}
                  />,
                ]
              );
            },
          }}
        >
          <ProFormText
            name="overtime_penalty_fee_min"
            label="罰款價格/分鐘"
            rules={[{ required: true }]}
            colProps={{ span: 6 }}
          />
          <ProFormDigit
            name="overtime_penalty_time_min"
            label="可以停留時間"
            rules={[{ required: true }]}
            colProps={{ span: 6, offset: 3 }}
          />
        </ProForm>
      </>
    );
  };

  const AdvertiseCard = () => {
    return (
      <>
        <BaseSearch
          title="Search bar"
          submitFun={actionRef.current?.reload}
          inputProps={{
            value: searchKey,
            onChange: ({ currentTarget: { value } }) => setSearchKey(value),
          }}
        />
        <BaseTable<API.Advertise>
          searchKey={searchKey}
          props={{
            headerTitle: '廣告列表',
            actionRef: advertiseActionRef,

            columns: AdvertiseColumns({
              mainTableReload: () => advertiseActionRef.current?.reload(),
            }),
            toolBarRender: () => [
              <CreateModal
                key="createModal"
                mainTableReload={() => advertiseActionRef.current?.reload()}
              />,
            ],
            request: async () => {
              const dataSource = await _getAdvertiseInfo();
              console.log('dataSource', dataSource);
              if (searchKey) {
                dataSource.data = Helper<API.Advertise>({
                  dataSource: dataSource.data,
                  keyWord: searchKey,
                }) as API.Advertise[];

                return dataSource;
              } else {
                return dataSource;
              }
            },
          }}
        />
      </>
    );
  };
  /**********************************組件初始化**********************************/
  /**********************************異步函數**********************************/
  /**********************************異步函數**********************************/
  return (
    <BaseIndex title="其他設定">
      <ProCard
        style={{ minHeight: '90vh' }}
        tabs={{
          tabPosition: 'left',
          activeKey: tab,
          items: [
            {
              label: `優惠券種類設置`,
              key: 'tab1',
              children: <CouponCard />,
            },
            {
              label: `時段優惠設置`,
              key: 'tab2',
              children: <PriceEventTable />,
            },
            // {
            //   label: `上傳車輛型號設定`,
            //   key: 'tab3',
            //   children: <div>Privacy policy</div>,
            // },
            {
              label: `罰款設定`,
              key: 'tab5',
              children: <PenaltyCard />,
            },
            {
              label: `廣告位相關設定`,
              key: 'tab6',
              children: <AdvertiseCard />,
            },
          ],
          onChange: (key) => {
            setTab(key);
          },
        }}
      />
    </BaseIndex>
  );
}
//
