import React, { useEffect, useState } from "react";
import {
  Form,
  Input,
  Modal,
  Select,
  message,
  Radio,
  Upload,
  InputNumber,
  DatePicker,
  Button,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { saveCarInfoApi, getAllSeriesApi } from "../api";
import { useStore } from "../index";
import { UploadFile } from "antd/lib/upload/interface";
import SpecCodeEdilt from "./SpecCodeEdilt";
import { cars } from "../interface";
import moment from "moment";
import * as DATA from '../carData';

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;

export default function CarModal() {
  const {
    brands,
    factorys,
    getFactories,
    series,
    getSeries,
    setLoading,
    visible,
    setVisible,
    setConfirmLoading,
    confirmLoading,
    currentItem,
    setCurrentItem,
    getSpecCodeList,
    specCodeList
  } = useStore();
  const [form] = Form.useForm();
  //新能源类型选择
  const [energryList, setEnergryList] = useState<any>(DATA.EnergyData);
  //控制隐藏
  const [exhaustHidden, setExhaustHidden] = useState(true); //排量
  const [inhaleTypeHidden, setInhaleTypeHidden] = useState(true); //进气方式
  const [gearboxHidden, setGearboxHidden] = useState(true); //变速箱
  const [envLevelHidden, setEnvLevelHidden] = useState(true); //环境标准
  const [batterySizeHidden, setBatterySizeHidden] = useState(true); //电池容量
  const [evMileageHidden, setEvMileageHidden] = useState(true); //纯电续航
  const [quickChargeHidden, setQuickChargeHidden] = useState(true); //快充
  const [slowChargeHidden, setSlowChargeHidden] = useState(true); //慢充

  //自动生成车型名称
  const [carName, setCarName] = useState<string>();
  const [restName, setRestName] = useState<string>();

  useEffect(() => {
    form.setFieldsValue({
      name: carName
    });
  }, [carName]);

  useEffect(() => {
    if (visible) {
      if (currentItem) {
        form.setFieldsValue({
          ...currentItem,
          year: currentItem.year && moment().year(currentItem.year),
          thumbnail: currentItem.thumbnail
            ? [
              {
                uid: "-1",
                name: "缩略图",
                status: "done",
                url: currentItem.thumbnail,
                response: { data: currentItem.thumbnail },
              },
            ]
            : [],
        });
        getFactories(currentItem.brandId);
        getSeries(currentItem.factoryId);
        getSpecCodeList(currentItem.seriesId);
        setCarName(currentItem.name);
      }
    }
  }, [visible]);

  useEffect(() => {
    if (visible) {
      if (currentItem) {
        getAllSeriesApi({ factoryId: currentItem.factoryId }).then((res: any) => {
          const car: any = res.data.filter(
            (item: any) => item.id === currentItem.seriesId
          );
          if (car[0].newEnergy) {
            setEnergryList(DATA.NewEnergyData);
          } else {
            setEnergryList(DATA.OldEnergyData);
          }
        });
      }
    }
  }, [visible]);

  useEffect(() => {
    if (visible) {
      if (currentItem) { //编辑
        if (currentItem.energyType === 1 || currentItem.energyType === 2) {
          setBatterySizeHidden(true);
          setEvMileageHidden(true);
          setQuickChargeHidden(true);
          setSlowChargeHidden(true);
          setExhaustHidden(false);
          setInhaleTypeHidden(false);
          setGearboxHidden(false);
          setEnvLevelHidden(false);
        } else if (currentItem.energyType === 6) {
          setBatterySizeHidden(false);
          setEvMileageHidden(false);
          setQuickChargeHidden(false);
          setSlowChargeHidden(false);
          setExhaustHidden(true);
          setInhaleTypeHidden(true);
          setGearboxHidden(true);
          setEnvLevelHidden(true);
        } else {
          setExhaustHidden(false);
          setInhaleTypeHidden(false);
          setGearboxHidden(false);
          setEnvLevelHidden(false);
          setBatterySizeHidden(false);
          setEvMileageHidden(false);
          setQuickChargeHidden(false);
          setSlowChargeHidden(false);
        }
      } else { // 新增
        setExhaustHidden(false);
        setInhaleTypeHidden(false);
        setGearboxHidden(false);
        setEnvLevelHidden(false);
        setBatterySizeHidden(false);
        setEvMileageHidden(false);
        setQuickChargeHidden(false);
        setSlowChargeHidden(false);
      }
    }
  }, [visible]);

  const okHandle = () => {
    form
      .validateFields()
      .then((v: any) => {
        const item = {
          ...v,
          id: currentItem ? currentItem.id : undefined,
          thumbnail: v.thumbnail ? v.thumbnail[0] && v.thumbnail[0].response.data : '',
          year: +moment(v.year).format("YYYY"),
          specCodeList: v.specCodeList,
        };
        setConfirmLoading(true);
        saveCarInfoApi(item)
          .then((res: any) => {
            message.success("操作成功！");
            setConfirmLoading(false);
            setVisible(false);
            setLoading(true);
          })
          .catch((error: any) => {
            message.error(error.message);
            setConfirmLoading(false);
          });
      })
      .catch((error) => {
        message.error(error.message);
        setConfirmLoading(false);
      });
  };

  const brandSelect = (v: any) => {
    form.setFieldsValue({
      factoryId: undefined,
      seriesId: undefined,
      energyType: undefined,
      ...DATA.resData,
    });
    setCarName("");
    return v;
  };

  const factorySelect = (v: any) => {
    form.setFieldsValue({
      seriesId: undefined,
      energyType: undefined,
      ...DATA.resData,
    });
    return v;
  };

  const seriesIdSelect = (v: any) => {
    form.setFieldsValue({
      energyType: undefined,
      ...DATA.resData,
    });
    setCarName("");
    const car: any = series.filter((item) => item.id === v);
    if (car[0].newEnergy) {
      setEnergryList(DATA.NewEnergyData);
    } else {
      setEnergryList(DATA.OldEnergyData);
    }
    return v;
  };

  const specCodeSelect = (v: string, options: any) => {
    const spec: OopSpecCode.ListVO[] = specCodeList.filter((item) => item.specCode === v);
    options.exhaust && form.setFieldsValue({
      exhaust: spec[0].exhaust,
      inhaleType: spec[0].inhaleType
    });
  };

  const beforeUpload = (file: UploadFile) => {
    const imgTypeArr = ["image/jpg", "image/jpeg", "image/gif", "image/png"];
    const isImg = imgTypeArr.indexOf(file.type) > -1;
    if (!isImg) {
      message.error("请选择png、jpg、gif、jpeg图片！");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片大小不能超过 2MB!");
    }
    return isImg && isLt2M;
  };

  const onPreView = (file: UploadFile) => {
    const bodyEl = document.body;
    const a = document.createElement("a");
    a.href = file.response.data;
    a.target = "__blank";
    bodyEl.appendChild(a);
    a.click();
    bodyEl.removeChild(a);
  };

  //选择能源类型
  const SelectEnergyType = (value: any) => {
    // form.setFieldsValue({ ...DATA.resData });
    // setCarName("");
    if (value === 1 || value === 2) {
      setBatterySizeHidden(true);
      setEvMileageHidden(true);
      setQuickChargeHidden(true);
      setSlowChargeHidden(true);
      setExhaustHidden(false);
      setInhaleTypeHidden(false);
      setGearboxHidden(false);
      setEnvLevelHidden(false);
    } else if (value === 6) {
      setBatterySizeHidden(false);
      setEvMileageHidden(false);
      setQuickChargeHidden(false);
      setSlowChargeHidden(false);
      setExhaustHidden(true);
      setInhaleTypeHidden(true);
      setGearboxHidden(true);
      setEnvLevelHidden(true);
    } else {
      setExhaustHidden(false);
      setInhaleTypeHidden(false);
      setGearboxHidden(false);
      setEnvLevelHidden(false);
      setBatterySizeHidden(false);
      setEvMileageHidden(false);
      setQuickChargeHidden(false);
      setSlowChargeHidden(false);
    }
  };

  //点击表单获取所有值并自动生成车型名称
  const onValuesChange = (changedValues: any, allValues: any) => {
    let NAME;
    if (currentItem === undefined) { //新增
      const caryear: string = allValues.year ? allValues.year.year() + "款" : "";
      const careditionName: string = allValues.editionName ? `${allValues.editionName}` : '';
      const carexhaust: string = allValues.exhaust ? `${allValues.exhaust.toFixed(1)}` : '';
      const carinhaleType: string = allValues.inhaleType ? (allValues.inhaleType === 1 ? "L" : "T") : '';
      const cardriveType: string = allValues.driveType ? `${DATA.DriveType[allValues.driveType]}` : '';
      const cartransmissionType: string = allValues.transmissionType ? `${DATA.TransmissionType[allValues.transmissionType]}` : '';
      const cargearbox: string = allValues.gearbox ? `${allValues.gearbox}` : '';
      const carmodelName: string = allValues.modelName ? allValues.modelName : '';
      const carsuitName: string = allValues.suitName ? `${allValues.suitName}` : '';
      const carseatCount: string = allValues.seatCount ? `${allValues.seatCount}座` : '';

      // const NAME = `${caryear} ${careditionName} ${carexhaust}${carinhaleType} ${cardriveType} ${cartransmissionType}${cargearbox} ${carmodelName} ${carsuitName} ${carseatCount}`;
      NAME = `${careditionName} ${carexhaust}${carinhaleType} ${cardriveType} ${cartransmissionType}${cargearbox} ${carmodelName} ${carsuitName} ${carseatCount}`;

      // let pattern = /\s+/g;
      // const _Name = NAME.replace(pattern, " ");
      // setCarName(_Name);
    } else { //编辑
      return;
      const caryear: string = allValues.year ? allValues.year.year() + "款" : "";
      const careditionName: string = allValues.editionName ? `${allValues.editionName}` : '';
      const carexhaust: string = allValues.exhaust ? `${allValues.exhaust.toFixed(1)}` : '';
      const carinhaleType: string = allValues.inhaleType ? (allValues.inhaleType === 1 ? "L" : "T") : '';
      const cardriveType: string = allValues.driveType ? `${DATA.DriveType[allValues.driveType]}` : '';
      const cartransmissionType: string = allValues.transmissionType ? `${DATA.TransmissionType[allValues.transmissionType]}` : '';
      const cargearbox: string = allValues.gearbox ? `${allValues.gearbox}` : '';
      const carmodelName: string = allValues.modelName ? allValues.modelName : '';
      const carsuitName: string = allValues.suitName ? `${allValues.suitName}` : '';
      const carseatCount: string = allValues.seatCount ? `${allValues.seatCount}座` : '';
      NAME = `${careditionName} ${carexhaust}${carinhaleType} ${cardriveType} ${cartransmissionType}${cargearbox} ${carmodelName} ${carsuitName} ${carseatCount}`;
    }
    let pattern = /\s+/g;
    const _Name = NAME.replace(pattern, " ");
    setCarName(_Name);
  };

  //重置车型名称
  const onRest = () => {
    if (currentItem) {
      if (carName === undefined && restName === undefined) {
        form.setFieldsValue({
          name: currentItem?.name,
        });
      } else {
        form.setFieldsValue({
          name: restName,
        });
      }
    } else {
      form.setFieldsValue({
        name: carName,
      });
    }
  };

  return (
    <Modal
      getContainer={false}
      width={900}
      title={`${currentItem ? "编辑" : "添加"}车型`}
      visible={visible}
      onOk={okHandle}
      maskClosable={false}
      onCancel={() => setVisible(false)}
      confirmLoading={confirmLoading}
      afterClose={() => {
        form.resetFields();
        setCurrentItem(undefined);
      }}
    >
      <Form
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 15 }}
        onValuesChange={onValuesChange}
      >
        <div
          style={{ display: "flex", flexDirection: "row", flexWrap: "wrap" }}
        >

          <FormItem
            style={{ width: 400 }}
            name="brandId"
            label="品牌"
            rules={[{ required: true, message: "必填项" }]}
            getValueFromEvent={brandSelect}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择品牌"
              onChange={(val) => getFactories(+val)}
            >
              {brands.map((item: cars.BrandItem) => (
                <Option key={item.id} value={item.id || 0} title={item.name}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="factoryId"
            label="厂商"
            rules={[{ required: true, message: "必填项" }]}
            getValueFromEvent={factorySelect}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择厂商"
              onChange={(val) => getSeries(+val)}
            >
              {factorys.map((item: cars.FactoryItem) => (
                <Option key={item.id} value={item.id || 0} title={item.name}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="seriesId"
            label="车系"
            rules={[{ required: true, message: "必填项" }]}
            getValueFromEvent={seriesIdSelect}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择"
              onChange={(val) => getSpecCodeList(+val)}
            >
              {series.map((item: cars.SeriesItem) => (
                <Option key={item.id} value={item.id || 0} title={item.name}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </FormItem>
          
          <FormItem
            style={{ width: 400 }}
            name="specCode"
            label="整车型号代码"
            rules={[{ required: true, message: "必填项" }]}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择"
              onChange={specCodeSelect}
            >
              {specCodeList.map((item: OopSpecCode.ListVO) => (
                <Option key={item.id} value={item.specCode || 0} exhaust={item.exhaust}>
                  {`[${item.specCode}]${item.specCodeName}`}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem
            name="specCodeList"
            label="配置代码"
            style={{ width: 400 }}
          >
            <SpecCodeEdilt />
          </FormItem>

          <FormItem
            name="thumbnail"
            valuePropName="fileList"
            label="缩略图"
            style={{ width: 400 }}
            // rules={[{ required: true }]}
            getValueFromEvent={(e) => {
              if (Array.isArray(e)) {
                return e.slice(-1);
              }
              if (!e.file.status) return [];
              if (e.file.status == "error") {
                message.error("缩略图上传出错，请重新上传");
                return [];
              }
              return e && e.fileList.slice(-1);
            }}
          >
            <Upload
              name="file"
              action="/api/oop/util/file/upload"
              accept="image/*"
              listType="picture-card"
              beforeUpload={beforeUpload}
              onPreview={onPreView}
            >
              <div>
                <PlusOutlined />
                <div className="ant-upload-text">上传缩略图</div>
              </div>
            </Upload>
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="name"
            label="配置名称"
            rules={[{ required: true, message: "该选项为必填项" }]}
          >
            <Input.TextArea autoSize allowClear />
          </FormItem>
          <FormItem
            name="classifyName"
            label="车型分类名称"
            style={{ width: 400 }}
            rules={[{ required: true, message: "该选项为必填项" }]}
          >
            <Input placeholder="请输入" allowClear />
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="energyType"
            label="能源类型"
            rules={[{ required: true }]}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择能源类型"
              onSelect={SelectEnergyType}
            >
              {energryList.map((item: any) => (
                <Option value={item.value} key={`${item.label}_${item.value}`}>
                  {item.label}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem
            name="year"
            label="年款"
            rules={[{ required: true }]}
            style={{ width: 400 }}
          >
            <DatePicker style={{ width: "100%" }} picker="year" />
          </FormItem>
          <FormItem
            name="exhaust"
            label="排量"
            rules={[{ required: !exhaustHidden }]}
            style={{ width: 400 }}
            hidden={exhaustHidden}
          >
            <InputNumber
              style={{ width: "100%" }}
              min={0}
              step={0.01}
              precision={1}
              placeholder="请输入排量"
            />
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="inhaleType"
            label="进气方式"
            hidden={inhaleTypeHidden}
            rules={[{ required: !inhaleTypeHidden }]}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择进气方式"
            >
              <Option value={1}>自然吸气</Option>
              <Option value={2}>涡轮增压</Option>
              <Option value={3}>机械增压</Option>
            </Select>
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="driveType"
            label="驱动类型"
          //rules={[{ required: true }]}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择驱动类型"
            >
              <Option value={1}>两驱</Option>
              <Option value={2}>四驱</Option>
            </Select>
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="transmissionType"
            label="变速类型"
          //rules={[{ required: true }]}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择变速类型"
            >
              <Option value={1}>手动</Option>
              <Option value={2}>自动</Option>
            </Select>
          </FormItem>
          <FormItem
            name="gearbox"
            label="变速箱"
            hidden={gearboxHidden}
            //rules={[{ required: true }]}
            style={{ width: 400 }}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择变速箱"
            >
              <Option value="MT">MT</Option>
              <Option value="AT">AT</Option>
              <Option value="CVT">CVT</Option>
              <Option value="DCT">DCT</Option>
              <Option value="DSGW">DSG</Option>
            </Select>
          </FormItem>
          <FormItem name="editionName" label="版本名称" style={{ width: 400 }}>
            <Input placeholder="请输入车型名称" />
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="modelName"
            label="型号名称"
            rules={[{ required: true }]}
          >
            <Input placeholder="请输入车型名称" />
          </FormItem>
          <FormItem
            name="suitName"
            label="套装名称"
            //rules={[{ required: true }]}
            style={{ width: 400 }}
          >
            <Input placeholder="请输入车型名称" />
          </FormItem>
          <FormItem
            name="batterySize"
            label="电池容量(kWh)"
            hidden={batterySizeHidden}
            //rules={[{ required: true }]}
            style={{ width: 400 }}
          >
            <InputNumber
              style={{ width: "100%" }}
              placeholder="请输入电池容量"
              min={0}
              precision={2}
            />
          </FormItem>
          <FormItem
            name="evMileage"
            label="纯电续航(km)"
            hidden={evMileageHidden}
            //rules={[{ required: true }]}
            style={{ width: 400 }}
          >
            <InputNumber
              style={{ width: "100%" }}
              min={0}
              precision={2}
              placeholder="请输入纯电续航"
            />
          </FormItem>
          <FormItem
            name="quickCharge"
            label="快充时间(小时)"
            hidden={quickChargeHidden}
            //rules={[{ required: true }]}
            style={{ width: 400 }}
          >
            <InputNumber
              style={{ width: "100%" }}
              min={0}
              precision={2}
              placeholder="请输入快充时间"
            />
          </FormItem>
          <FormItem
            name="slowCharge"
            label="慢充时间(小时)"
            hidden={slowChargeHidden}
            //rules={[{ required: true }]}
            style={{ width: 400 }}
          >
            <InputNumber
              style={{ width: "100%" }}
              min={0}
              precision={2}
              placeholder="请输入慢充时间"
            />
          </FormItem>
          <FormItem
            name="envLevel"
            label="排放标准"
            hidden={envLevelHidden}
            rules={[{ required: !envLevelHidden }]}
            style={{ width: 400 }}
          >
            <Select
              allowClear
              showSearch
              optionFilterProp="children"
              style={{ width: "100%" }}
              placeholder="请选择排放标准"
            >
              <Option value="国I">国I</Option>
              <Option value="国II">国II</Option>
              <Option value="国III">国III</Option>
              <Option value="国IV">国IV</Option>
              <Option value="国V">国V</Option>
              <Option value="国VI">国VI</Option>
            </Select>
          </FormItem>
          <FormItem
            name="seatCount"
            label="座位数"
            //rules={[{ required: true }]}
            style={{ width: 400 }}
          >
            <InputNumber
              style={{ width: "100%" }}
              min={0}
              step={1}
              placeholder="请输入座位数"
            />
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="saleStatus"
            label="销售状态"
            rules={[{ required: true }]}
          >
            <RadioGroup>
              <Radio value={1}>在售</Radio>
              <Radio value={0}>停售</Radio>
              <Radio value={2}>预售</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            style={{ width: 400 }}
            name="proStatus"
            label="生产状态"
            rules={[{ required: true }]}
          >
            <RadioGroup>
              <Radio value={1}>在产</Radio>
              <Radio value={0}>停产</Radio>
            </RadioGroup>
          </FormItem>

        </div>
      </Form>
      {!currentItem && (
        <Button
          type="primary"
          style={{ display: "block", margin: "auto" }}
          onClick={onRest}
        >
          重置名称
        </Button>
      )}
    </Modal>
  );
}
