import React, { useEffect , useState , useContext } from 'react'
import {useRouter} from 'next/router';
import Layout from "~/components/layout";
import {Box} from './styled';
import ImagePreview from './components/picture-preview';
import { Button , Image as AImage , Divider , Select,Modal ,Tag,Space,Form,message} from 'antd';
import Image from 'next/image';
import errImg from "~/assets/errImg";
import api,{GetWebDeviceDetailResult,GetWebDeviceWareSkuById} from './api';
import { UserContext } from "~/lib/userProvider";
import flowPat from './assets/flow-path.png'

const { CheckableTag } = Tag

export default function EquipmentLeasingDetail() {
  const router = useRouter();
  const { userInfo, setNeedLogin } = useContext(UserContext);
  const [id, setId] = useState<number | null>(null);
  
  const [detail,setDetail] = useState<GetWebDeviceDetailResult | null>()
  const [wareSkuList,setWareSkuList] = useState<GetWebDeviceWareSkuById[] | undefined>()

  useEffect(()=>{
    setId(Number(router.query.id))
  },[router])

  useEffect(()=>{
    if (id) {
      api
        .listDetailDeviceInfo({
          id:id
        })
        .then((res) => {
          setDetail(res.result || null);
        });
      api
        .listWareSkuById({
          id:id
        })
        .then((res) => {
          res.result?.map(item=>{
            return item
          })
          setWareSkuList(res.result || undefined);
        });
    }
  },[id])

  //租赁弹框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const tagsData = ['3-7天', '8-15天', '16-30天', '30天以上'];
  const [selectedTags, setSelectedTags] = useState<number>();
  const [selectedTagsData, setSelectedTagsData] = useState<string>();

  const showModal = () => {
    if (userInfo) {
      setIsModalOpen(true);
      if (wareSkuList?.length) {
        setSelectedTags(wareSkuList[0].id);
        form.setFieldValue("id",wareSkuList[0].id)
        setSelectedTagsData("3-7天")
        form.setFieldValue("date","3-7天")
      }
    }else{
      setNeedLogin(true)
    }
  };

  const handleOk = () => {
    setLoading(true);
    form
    .validateFields()
    .then(async (values) => {
      form.resetFields()
      message.success("租赁成功")
      setLoading(false);
      setIsModalOpen(false);
    //   try{
    //    const res = await api.listWareSkuUpdate(values)
    //    if (res.code === "200") {
    //    setLoading(false);
    //    setIsModalOpen(false);
    //    form.resetFields()
    //    message.success('租赁成功')
    //    }else{
    //      setLoading(false);
    //      message.error(res.message)
    //    }
       
    //  }catch(e:any){
    //    message.error(e.message)
    //  }
    }).catch((err) => {
     message
       .warning({
         content: err.errorFields[0].errors[0],
       })
       .then();
       setLoading(false);
   });
     
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  
  const handleChange = (tag: number, checked: boolean) => {
   if (checked) {
    const nextWareSkuList = checked
    ? tag
    : wareSkuList?.filter((t) => t.id !== tag)[0].id;
    console.log('You are interested in: ', nextWareSkuList);
    setSelectedTags(nextWareSkuList);
    form.setFieldValue("id",tag)
   }
  };

  const handleChangeDate = (tag: string, checked: boolean) => {
    if (checked) {
      const nextSelectedTags = checked
      ?  tag
      : tagsData.filter((t) => t !== tag)[0];
    console.log('You are interested in: ', nextSelectedTags);
    setSelectedTagsData(nextSelectedTags);
    form.setFieldValue("date",tag)
    }
  };

  return (
    <Layout>
      <Box>
        <div className='item'>
          <ImagePreview imgList={detail?.wareImgs!}/>
          <div className='item-right'>
            <div className='title'>{detail?.wareTitle}</div>
              {
                detail?.tags?.length ? 
                (<div className='function'>
                {detail?.tags?.map(item=>(<div key={item} className='function-item'>{item}</div>))}
               </div>) : (<div className='function not'></div>)
              }
            <div className='menoy'>
              <span className='menoy-left'>{`¥${detail?.minRent}`}</span>
              <span className='menoy-right'>/天起</span>
            </div>
            <div className='classification'>
              <div className='top'>
                <div className='left'>
                  <span className='label'>选择</span>
                  <span className='value'>商品分类</span>
                </div>
                <div className='right'>
                <Select
                    className="selectItem"
                    defaultActiveFirstOption
                    defaultValue={wareSkuList}
                    style={{ width: 120 }}
                    bordered={false}
                    options={wareSkuList}
                    fieldNames={{label:"skuTitle",value:"id"}}
                    placeholder="选择商品"
                  />
                </div>
              </div>
              <div className='bottom'>
              <span className='label'>发货</span>
                  <span className='value'>顺丰到付</span>
              </div>
            </div>
            <div className='botton-btn'>
                  {/* <Button className='btn-left' size='small' type="primary">成为渠道商</Button> */}
                  <Button className='btn-right' size='small' type="primary" onClick={showModal}>立即租赁</Button>
            </div>
          </div>
        </div>
        <div className='flow-path'>
              <Image className='image' fill src={flowPat.src} alt="" />
        </div>
        <div className='prompt'>
          更多租金规则请前往【云享飞】微信小程序查
        </div>
        <Divider className='divider'>商品详情</Divider>
        {
          detail?.wareDetailContent ? <div style={{ textAlign: "center" }} dangerouslySetInnerHTML={{ __html: detail?.wareDetailContent}}>
          </div> : <div style={{ textAlign: "center" }} ></div>
        }
      {/* 立即租赁 */}
      <Modal
       wrapClassName='application'
       open={isModalOpen}
       onOk={handleOk}
       onCancel={handleCancel}
       getContainer={false}
       footer={[
        <Button
          style={{ width: "100%" ,height: 44 }}
          key="submit"
          type="primary"
          loading={loading}
          onClick={handleOk}
        >
          立即租赁
        </Button>,
      ]}
      >
        <div className='title'>
          <div className="left"></div>
          <div className="right">
            <div className="top">
            <span className='tag'>¥</span>
            <span className='money'>{detail?.minRent}</span>
            <span className='unit'>/天</span>
            </div>
            <div className="bottom">渠道免押金</div>
          </div>
        </div>
      <Form
        form={form}
        layout="vertical"
        name="application"
        initialValues={{ modifier: 'public' }}
      >
      <Form.Item style={{flex:1,marginRight:16}} name="id" label="选择商品">
       <Space size={[0, 8]} wrap>
       {wareSkuList?.map((tag) => (
         <CheckableTag
           style={{height:28,lineHeight:"28px"}}
           key={tag.id}
           checked={wareSkuList?.some(item=>tag.id === selectedTags)}
           onChange={(checked) => handleChange(tag.id, checked)}
         >
           {tag.skuTitle}
         </CheckableTag>
       ))}
      </Space>
      </Form.Item>
      <Form.Item style={{flex:1,marginRight:16}} name="date" label="租期天数（拿到和归还当天不算入租期）">
      <Space size={[0, 8]} wrap>
        {tagsData.map((tag) => (
          <CheckableTag
            key={tag}
            checked={tag === selectedTagsData}
            onChange={(checked) => handleChangeDate(tag, checked)}
          >
            {tag}
          </CheckableTag>
        ))}
      </Space>
      </Form.Item>
      </Form>
      </Modal>
      </Box>
    </Layout>
  )
}
