import './index.scss';
import { Button, Col, Form, Radio, Row, Select } from 'antd';
import { OrderManageAPI, RentManageAPI, SystemManageAPI } from '~/api';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import AddOrEditAddressModal from '~/pages/systemManage/addressManage/components/addOrEditAddressModal';
import { InterDataType } from '~/api/interface';
import { leaseGoodsDetailsType } from '~/api/interface/rentManageType';

//租赁商品详情返回类型
type rentGoodsDetailType = InterDataType<leaseGoodsDetailsType>;
interface selfProps {
  ref: any;
  rentGoodsDetails: rentGoodsDetailType | undefined;
}

const AddressInfo = forwardRef<any, selfProps>(({ rentGoodsDetails }, ref) => {
  const [addressInfoForm] = Form.useForm<{
    shipAddress: number;
    returnAddress: number;
    logisticsCompany: string;
    modeOfDelivery: number;
  }>();

  const [addOrEditAddressModalShow, setAddOrEditAddressModalShow] = useState<boolean>(false);
  // 当前用户地址列表
  const [addressOptionList, setAddressOptionList] = useState<
    { label: string; value: number; districtCode: string }[]
  >([]);
  // 编辑查询的某个用户地址
  const [addressItem, setAddressItem] = useState<{
    label: string;
    value: number;
    districtCode: string;
  }>();

  const [expressOptionList, setExpressOptionList] = useState<{ label: string; value: string }[]>(
    [],
  );
  //配送方式
  const [shippingMethodList, setShippingMethodList] = useState<
    { id: number; saleServiceName: string }[]
  >([]);

  useImperativeHandle(ref, () => ({
    addressInfoFormSubmit,
    getForm: () => addressInfoForm,
  }));

  //地址列表
  const getAddressList = () => {
    SystemManageAPI.getAddressList({}).then(({ result }) => {
      if (result) {
        const optionList = result.map((v) => ({
          label: v.takeName + v.takePhone + `(${v.takeRegion.split('/').join('') + v.takeAddress})`,
          value: v.id,
          districtCode: v.districtCode,
        }));
        const addressItemObj = result.find((v) => v.type === 0);
        if (addressItemObj && !addressItem) {
          addressInfoForm.setFieldsValue({
            returnAddress: addressItemObj.id,
            shipAddress: addressItemObj.id,
          });
        }
        setAddressOptionList(optionList);
      }
    });
  };
  //物流公司列表
  const getListExpressInfo = () => {
    OrderManageAPI.listExpressInfo().then(({ result }) => {
      if (result) {
        const optionList = result.map((v) => ({
          label: v.exName,
          value: v.exCode,
        }));
        setExpressOptionList(optionList);
      }
    });
  };
  //物流-配送方式
  const getOtherService = () => {
    RentManageAPI.getOtherServiceList().then(({ result }) => {
      setShippingMethodList(result || []);
    });
  };
  //物流表单提交
  const addressInfoFormSubmit = () => {
    return new Promise((resolve, reject) => {
      addressInfoForm
        .validateFields()
        .then((values) => {
          resolve({
            ...values,
            districtCode: addressOptionList.find((v) => v.value === values.shipAddress)
              ?.districtCode,
          });
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  //新增地址弹窗
  const addAddressClick = () => [setAddOrEditAddressModalShow(true)];
  const addOrEditAddressModalOk = () => {
    getAddressList();
    setAddOrEditAddressModalShow(false);
  };
  const addOrEditAddressModalCancel = () => {
    setAddOrEditAddressModalShow(false);
  };
  // 获取地址
  const getUserAddressInfo = (userAddressId: number) => {
    SystemManageAPI.getUserAddressInfo({ userAddressId }).then(({ result }) => {
      if (result) {
        setAddressItem({
          value: result.id,
          label:
            result.takeName +
            result.takePhone +
            `(${result.takeRegion.split('/').join('') + result.takeAddress})`,
          districtCode: result.districtCode,
        });
      }
    });
  };

  useEffect(() => {
    getAddressList();
    getListExpressInfo();
    getOtherService();
  }, []);

  useEffect(() => {
    if (rentGoodsDetails) {
      getUserAddressInfo(rentGoodsDetails.shipAddress);
      getUserAddressInfo(rentGoodsDetails.returnAddress);
      addressInfoForm.setFieldsValue({
        shipAddress: rentGoodsDetails.shipAddress,
        returnAddress: rentGoodsDetails.returnAddress,
        logisticsCompany: rentGoodsDetails.logisticsCompany,
        modeOfDelivery: rentGoodsDetails.modeOfDelivery,
      });
    }
  }, [rentGoodsDetails]);
  return (
    <div className='address-info'>
      <div className='address-info-title'>物流信息</div>
      <Form labelCol={{ span: 2 }} wrapperCol={{ span: 10 }} form={addressInfoForm}>
        <Form.Item
          label='发货地址'
          name='shipAddress'
          rules={[{ required: true, message: '请选择发货地址' }]}
        >
          <Select
            placeholder='请选择发货地址'
            options={addressItem ? [...addressOptionList, addressItem] : addressOptionList}
          ></Select>
        </Form.Item>
        <Form.Item>
          <Row>
            <Col span={5}></Col>
            <Col>
              <Button type='link' icon={<PlusOutlined />} onClick={addAddressClick}>
                新增地址
              </Button>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item
          label='归还地址'
          name='returnAddress'
          rules={[{ required: true, message: '请选择归还地址' }]}
        >
          <Select
            placeholder='请选择归还地址'
            options={addressItem ? [...addressOptionList, addressItem] : addressOptionList}
          ></Select>
        </Form.Item>
        <Form.Item>
          <Row>
            <Col span={5}></Col>
            <Col>
              <Button type='link' icon={<PlusOutlined />} onClick={addAddressClick}>
                新增地址
              </Button>
            </Col>
          </Row>
        </Form.Item>
        <Form.Item
          label='寄出物流'
          name='logisticsCompany'
          rules={[{ required: true, message: '请选择寄出物流' }]}
        >
          <Select placeholder='请选择寄出物流' options={expressOptionList}></Select>
        </Form.Item>
        <Form.Item
          label='配送方式（寄出）'
          name='modeOfDelivery'
          rules={[{ required: true, message: '请选择配送方式（寄出）' }]}
        >
          <Radio.Group>
            {shippingMethodList.map((v) => (
              <Radio value={v.id} key={v.id}>
                {v.saleServiceName}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>
      </Form>
      <AddOrEditAddressModal
        open={addOrEditAddressModalShow}
        onOk={addOrEditAddressModalOk}
        onCancel={addOrEditAddressModalCancel}
      />
    </div>
  );
});
export default AddressInfo;
