import React, { useState, useEffect } from 'react';
import { Button, Form, message, InputNumber, Select, Modal} from 'antd';
import ShopSelectNew from '@/components/ShopSelectNew';
import { debounce } from 'lodash';
import currency from 'currency.js';
import useInitail from '@/hooks/useInitail';
import { useStore } from '../index';
import { saveRetailConfigApi } from '../api';

const Option = Select.Option;

export default function Index() {
  const [form] = Form.useForm();
  const { visible, setVisible, current, setCurrent, setLoading } = useStore();
  const [confirm, setConfirm] = useState<boolean>(false);

  useEffect(() => {
    if (visible && current.id) {
      handleSetValue();
    }
  }, [visible]);

  function handleCancle() {
    setVisible(false);
    setCurrent({});
  }

  async function handleSubmit() {
    const params = await form.validateFields();
    setConfirm(true);
    const _params = {
      id: current.id,
      retailRate: params.retailRate,
      shopList: params.shopList?.map((v: any) => ({shopId: v.value, shopName: v.label}))
    };
    saveRetailConfigApi(_params)
    .then(res => {
      message.success(res.result);
      setVisible(false);
      setConfirm(false);
      setLoading(true);
      setCurrent({});
    })
    .catch(e => {
      message.error(e.message);
      setConfirm(false);
    });
  }

  function handleSetValue() {
    form.setFieldsValue({
      retailRate: current.retailRate,
      shopList: current.shopList?.map(v => ({label: v.shopName, value: v.shopId}))
    });
  }
  return (
    <Modal
      title={current.id ? "编辑" : "新增"}
      destroyOnClose
      visible={visible}
      maskClosable={false}
      onCancel={handleCancle}
      afterClose={() => form.setFieldsValue({shopList: [], retailRate: undefined})}
      style={{minWidth: "500px"}}
      footer={[
        <Button key="cancel" onClick={handleCancle} style={{marginLeft: 10}}>取消</Button>,
        <Button key="submit" onClick={handleSubmit} type="primary" htmlType="submit" loading={confirm}>确认</Button>
        ]}
    >
      <Form
        form={form}
        labelCol={{ span: 10 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item
          label="适用门店"
          name="shopList"
          rules={[{ required: true, message: "请选择门店" }]}
          labelAlign="right"
        >
          <ShopSelectNew defaultOptions={{bizTypes: "1"}} placeholder="请选择门店" multiple />
        </Form.Item>

        <Form.Item
          label="线索到店零售台数占比"
          name="retailRate"
          rules={[{ required: true, message: "请输入" }]}
        >
          <InputNumber
            style={{width: '100%'}}
            controls={false}
            min={0}
            max={100}
            formatter={value => `${value}%`}
            precision={2}
            parser={value => value?.replace('%', '')}
          />
        </Form.Item>
        
      </Form>

    </Modal>
  );
}