import React, { useState, useEffect } from 'react';
import { Modal, Button, message, Form, InputNumber, DatePicker, Radio, Row, Col } from 'antd';
import {useStore} from '../index';
import {ListResult, saveConfigApi} from '../api';
import { debounce, isNil } from 'lodash';
import ShopSelectNew from '@/components/ShopSelectNew';
import moment from 'moment';
import '../index.less';

const { RangePicker } = DatePicker;

export default function DetailModal() {
  const {currentData, setCurrentData, setLoading} = useStore();
  const [confirm, setConfirm] = useState<boolean>(false);
  const [type, setType] = useState<number>(2);
  const [form] = Form.useForm();

  useEffect(() => {
    if (currentData.visible && currentData.data.id) {
      handleSetValue();
    } else {
      form.setFieldsValue({addedValueType: 2});
    }
  }, [currentData.visible]);

  const handleChangeType = (value: number) => {
    setType(value);
    if (value === 1) {
      form.setFieldsValue({
        tciOutputValueRatio: 100,
        vciOutputValueRatio: 100,
        jcxOutputValueRatio: 100,
        decoOutputValueRatio: 100,
      });
    } else if (value === 2) {
      form.setFieldsValue({
        tciOutputValueRatio: 0,
        vciOutputValueRatio: 0,
        jcxOutputValueRatio: 0,
        decoOutputValueRatio: 0,
      });
    }
  };

  const handleCancel = () => {
    form.resetFields();
    setCurrentData({visible: false, data: {}, title: ""});
    setType(2);
  };

  const handleSetValue = () => {
    form.setFieldsValue({
      addedValueTask: currentData.data?.addedValueTask,
      tciOutputValueRatio: currentData.data?.tciOutputValueRatio,
      vciOutputValueRatio: currentData.data?.vciOutputValueRatio,
      jcxOutputValueRatio: currentData.data?.jcxOutputValueRatio,
      decoOutputValueRatio: currentData.data?.decoOutputValueRatio,
      shopList: currentData.data?.shopList?.map((v: any) => ({value: v.shopId, label: v.shopName})) || [],
      rangeDate: [moment(currentData.data.beginTime), moment(currentData.data.endTime)],
      addedValueType: currentData?.data?.addedValueType,
      vciOutputValueTask: currentData?.data?.vciOutputValueTask,
      decoOutputValueTask: currentData?.data?.decoOutputValueTask
    });
    setType(currentData.data?.addedValueType || 2);
  };

  const onFinish = async () => {
    const params = await form.validateFields();
    setConfirm(true);
    const _params: ListResult = {
      id: currentData.data?.id,
      addedValueTask: params.addedValueTask,
      tciOutputValueRatio: params.tciOutputValueRatio,
      vciOutputValueRatio: params.vciOutputValueRatio,
      jcxOutputValueRatio: params.jcxOutputValueRatio,
      decoOutputValueRatio: params.decoOutputValueRatio,
      shopList: params.shopList.map((v: any) => ({shopId: v.value, shopName: v.label})),
      beginTime: moment(params.rangeDate[0]).valueOf(),
      endTime: moment(params.rangeDate[1]).valueOf(),
      addedValueType: params.addedValueType,
      vciOutputValueTask: params.vciOutputValueTask,
      decoOutputValueTask: params.decoOutputValueTask
    };
    saveConfigApi(_params)
    .then(res => {
      message.success(res.result);
      setConfirm(false);
      setLoading(true);
      handleCancel();
    })
    .catch(e => {
      setConfirm(false);
      message.error(e.message);
    });
  };

  return (
    <Modal
      destroyOnClose
      forceRender
      title={currentData.title}
      open={currentData.visible}
      maskClosable={false}
      onCancel={handleCancel}
      width="50%"
      footer={[
        <Button key="cancel" onClick={handleCancel} style={{marginLeft: 10}}>取消</Button>,
        <Button key="submit" onClick={debounce(onFinish, 380)} type="primary" htmlType="submit" loading={confirm}>确认</Button>
        ]}
    >
      <Form
        form={form}
        labelAlign="left"
        style={{marginLeft: 30, marginRight: 30}}
      >
        <Form.Item name="addedValueType">
          <Radio.Group onChange={(e) => handleChangeType(e.target.value)} defaultValue={2} buttonStyle="solid">
            <Radio.Button value={2}>按毛利计算</Radio.Button>
            <Radio.Button value={1}>按产值计算</Radio.Button>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label={type === 2 ? "单车附加值毛利目标" : "单车附加值产值目标"}
          name="addedValueTask"
          rules={[{ required: true, message: "请输入" }]}
        >
          <InputNumber
            style={{width: '100%'}}
            controls={false}
            min={0}
            formatter={(value: any) => `${value}元/台`}
            precision={2}
            parser={(value: string) => value?.replace('元/台', '')}
          />
        </Form.Item>
        <Row style={{marginLeft: 30}}>

          <Form.Item
            label={<span>其中：<span>商业险产值目标</span></span>}
            name="vciOutputValueTask"
            style={{width: '100%'}}
            rules={[({ getFieldValue }) => ({
                validator(_, value) {
                  if (isNil(value)) {
                    return Promise.reject(new Error('请输入'));
                  }
                  return Promise.resolve();
                },
              })]}
          >
            <InputNumber
              style={{width: '100%'}}
              controls={false}
              min={0}
              formatter={(value: any) => `${value}元/台`}
              precision={2}
              parser={(value: string) => value?.replace('元/台', '')}
            />
          </Form.Item>
          <Form.Item
            label={<span style={{textIndent: '42px'}}>装潢产值目标</span>}
            name="decoOutputValueTask"
            style={{width: '100%'}}
            rules={[({ getFieldValue }) => ({
                validator(_, value) {
                  if (isNil(value)) {
                    return Promise.reject(new Error('请输入'));
                  }
                  return Promise.resolve();
                },
              })]}
          >
            <InputNumber
              style={{width: '100%'}}
              controls={false}
              min={0}
              formatter={(value: any) => `${value}元/台`}
              precision={2}
              parser={(value: string) => value?.replace('元/台', '')}
            />
          </Form.Item>
        </Row>

        <div className="addValue_wrapper"><span className="addvalue_text">&#65290;</span><span>产值构成：</span></div>
        <Form.Item
          label={type === 2 ? "1.计算保险毛利" : "1.计算保险产值："}
        >
          <Form.Item
            label={<span className="addValue_label">商业险金额 x</span>}
            name="vciOutputValueRatio"
            colon={false}
            rules={[({ getFieldValue }) => ({
                validator(_, value) {
                  if (isNil(value)) {
                    return Promise.reject(new Error('请输入'));
                  }
                  return Promise.resolve();
                },
              })]}
          >
            <InputNumber
              style={{width: '100%'}}
              controls={false}
              disabled={type === 1}
              min={0}
              max={100}
              formatter={(value: any) => `${value}%`}
              precision={2}
              parser={(value?: string) => value?.replace('%', '')}
            />
          </Form.Item>
          <Form.Item
            label={<span className="addValue_label">交强险金额 x</span>}
            colon={false}
            name="tciOutputValueRatio"
            rules={[({ getFieldValue }) => ({
                validator(_, value) {
                  if (isNil(value)) {
                    return Promise.reject(new Error('请输入'));
                  }
                  return Promise.resolve();
                },
              })]}
          >
            <InputNumber
              style={{width: '100%'}}
              controls={false}
              disabled={type === 1}
              min={0}
              max={100}
              formatter={(value: any) => `${value}%`}
              precision={2}
              parser={(value?: string) => value?.replace('%', '')}
            />
          </Form.Item>
          <Form.Item
            label={<span className="addValue_label">驾意险金额 x</span>}
            colon={false}
            name="jcxOutputValueRatio"
            rules={[({ getFieldValue }) => ({
                validator(_, value) {
                  if (isNil(value)) {
                    return Promise.reject(new Error('请输入'));
                  }
                  return Promise.resolve();
                },
              })]}
          >
            <InputNumber
              style={{width: '100%'}}
              controls={false}
              disabled={type === 1}
              min={0}
              max={100}
              formatter={(value: any) => `${value}%`}
              precision={2}
              parser={(value?: string) => value?.replace('%', '')}
            />
          </Form.Item>
        </Form.Item>
        <Form.Item
          label={<span style={{fontSize: '14px'}}><span style={{color: "#333"}}>2.{type === 2 ? "计算装潢毛利" : "计算装潢产值"}：</span><span className="addValue_label">装潢金额 x</span></span>}
          colon={false}
          name="decoOutputValueRatio"
          rules={[({ getFieldValue }) => ({
              validator(_, value) {
                if (isNil(value)) {
                  return Promise.reject(new Error('请输入'));
                }
                return Promise.resolve();
              },
            })]}
        >
          <InputNumber
            style={{width: '100%'}}
            controls={false}
            disabled={type === 1}
            min={0}
            max={100}
            formatter={(value: any) => `${value}%`}
            precision={2}
            parser={(value?: string) => value?.replace('%', '')}
          />
        </Form.Item>
        <div style={{marginBottom: '25px'}}>
          <span style={{color: "#333", fontSize: '14px'}}>3.其他附加值：</span>
          <span style={{color: "#F4333C", fontSize: '14px'}}>分期附加费</span>
          <span style={{color: "#999", fontSize: '12px'}}>（包含服务费、GPS费、抵押上户费、解除抵押费）</span>
          <span style={{color: "#F4333C", fontSize: '14px'}}>和全款上户费要按实收计算</span>
        </div>
        <Form.Item
          label="适用门店"
          name="shopList"
          rules={[{ required: true, message: "请输入" }]}
        >
          <ShopSelectNew defaultOptions={{bizTypes: "1"}} placeholder="请选择门店" multiple />
        </Form.Item>
        <Form.Item
          label="生效时间"
          name="rangeDate"
          rules={[{ required: true, message: "请输入" }]}
        >
          <RangePicker disabled={!!currentData.data.id} disabledDate={(current) => current && current < moment().startOf('day')} picker="month" format="YYYY-MM" />
        </Form.Item>
      </Form>
    </Modal>
  );
}