import React, { useState, useEffect } from 'react';
import { Card, Button, message, Checkbox } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { getSettingApi, saveSettingApi } from './api';
import { debounce } from 'lodash';

export default function InsuranceSetting() {
  const option = [
    {label: "服务费", value: 'financeServiceFee'}, 
    {label: "抵押上户费", value: 'mortgageRegisterFee'}, 
    {label: "解除抵押费", value: 'removeMortgageFee'}, 
    {label: "GPS费", value: 'gpsFee'}];
  const [checked, setChecked] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [disabled, setDisabled] = useState<boolean>(false);

  useEffect(() => {
    getData();
  }, []);

  function getData() {
    setLoading(true);
    getSettingApi()
    .then(res => {
      const data = res.data;
      if (data) {
        let _check = [];
        for (let k in data) {
          if (data[k]) {
            _check.push(`${k}`);
          }
      }
      setChecked(_check);
      setLoading(false);
    }
    })
    .catch(e => {
      message.error(e.message);
      setLoading(false);
    });
  }

  function onChange(value?: any) {
    value && setChecked(value);
  }

  const onSubmit = () => {
    setDisabled(true);
    const params = {
      financeServiceFee: checked.includes('financeServiceFee'),
      mortgageRegisterFee: checked.includes('mortgageRegisterFee'),
      removeMortgageFee: checked.includes('removeMortgageFee'),
      gpsFee: checked.includes('gpsFee')
    };
    saveSettingApi(params)
    .then(res => {
      message.success(res.result);
      getData();
      setDisabled(false);
    })
    .catch(e => {
      message.error(e.message);
      setDisabled(false);
    });
  }
  return (
    <PageHeaderWrapper loading={loading} title="分期优惠券可抵扣订单款项设置">
      <Card>
        <div style={{marginBottom: 20}}>
          <Checkbox.Group defaultValue={checked} options={option} onChange={(value) => onChange(value)} />
        </div>
        <div>
          <Button loading={disabled} onClick={debounce(onSubmit, 380)} type="primary">确定</Button>
        </div>
      </Card>
    </PageHeaderWrapper>
  );
}