import {ProForm, ProFormInstance, ProFormSelect, ProFormText} from '@ant-design/pro-components';
import {message} from 'antd';
import React, {useRef} from 'react';
import {getConfigGetApi, postConfigSaveApi} from "@/services/swagger/configAdmin";

const options = [
  {
    value: '1',
    label: '紫币',
  },
  {
    value: '2',
    label: '紫晶',
  },
]

type SignSetting = {
  dayCnt: number;
  awardCnt: number;
  awardType: number;
};

export default () => {
  const formRef = useRef<ProFormInstance>();
  const days = Array.from({length: 7}, (_, i) => i + 1);

  return (
    <ProForm
      layout="horizontal"
      title="签到设置"
      formRef={formRef}
      submitter={{}}
      request={async () => {
        const res = await getConfigGetApi({"code": "platform.sign.award"})
        if (res.success && res.data.content) {
          const result: SignSetting[] = JSON.parse(res.data.content)
          return result.reduce((acc: any, item: SignSetting) => {
            acc[`day${item.dayCnt}AwardCnt`] = item.awardCnt;
            acc[`day${item.dayCnt}AwardType`] = item.awardType.toString();
            return acc;
          }, {});
        }

        return Promise.resolve({});
      }}
      onFinish={async (values) => {
        const result: SignSetting[] = days.map(day => ({
          dayCnt: day,
          awardCnt: values[`day${day}AwardCnt`],
          awardType: values[`day${day}AwardType`],
        }));
        console.log("value " + values);
        console.log("result " + result);

        const res = await postConfigSaveApi({
          "type": "json",
          "code": "platform.sign.award",
          "remark": "签到奖励配置",
          "content": JSON.stringify(result)
        })

        if (res.success) {
          message.success('提交成功');
        } else {
          message.error(res.errorMessage)
        }
        return res.success;
      }}
    >

      {days.map(day => (
        <ProForm.Group key={day}>
          <ProFormText name={`day${day}AwardCnt`} width="md" label={`第${day}天`}/>
          <ProFormSelect name={`day${day}AwardType`} options={options} initialValue="1" width="xs"/>
        </ProForm.Group>
      ))}
    </ProForm>
  );
};
