import React, { useEffect, useState } from 'react';
import {
  RightOutlined,
  SafetyCertificateFilled,
  VerticalAlignTopOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useDispatch, useSelector } from 'react-redux';
import styled from 'styled-components';
import { HomeAPI } from '@/api';
import { InterDataType } from '@/api/interface';
import { AppPublishListType } from '@/api/interface/home';
import QrcodePopover from '@/components/qrcodePopover';
import { setGlobalData } from '@/store/module/globalData';
import { UserInfoState } from '@/store/module/userInfo';
import { formatLocationStr } from '@/utils/formatLocation';
import { bigNumberTransform } from '@/utils/money';

// 列表类型
type ListType = InterDataType<AppPublishListType>;

const HomeTaskView = () => {
  // store
  const dispatch = useDispatch();
  // userInfo
  const userInfo = useSelector((state: any) => state.userInfo) as UserInfoState;
  // 服务标签类型
  const serviceTagList = [
    {
      label: '加急单',
      code: 'RUSH_ORDER',
      color: '#FF0000',
      text: '急',
    },
    {
      label: '置顶单',
      code: 'TOP_ORDER',
      color: '#FF7A2C',
      icon: (
        <VerticalAlignTopOutlined style={{ color: '#fff', fontSize: 10 }} />
      ),
    },
  ];
  // 保险列表
  const insuranceList = [
    { name: '飞手险', value: 1 },
    { name: '机身险', value: 2 },
    { name: '三者险', value: 3 },
  ];
  // 实时订单列表
  const [requireList, setRequireList] = useState<ListType>([]);
  // 获取实时订单列表
  const getAppPublishList = async () => {
    const res = await HomeAPI.appPublishList({
      isNewRequirements: true,
    });
    if (res && res.code === '200') {
      const list = res.result || [];
      setRequireList(
        list.slice(0, 4),
        // .map((i) => ({
        //   ...i,
        //   orderLevelEnum: 'RUSH_ORDER',
        //   requireDescription:
        //     '红鲤鱼绿鲤鱼与驴，红鲤鱼绿鲤鱼与驴，红鲤鱼绿鲤鱼与驴',
        //   orderAmount: 999999,
        // })),
      );
    }
  };
  // 需求类型列表
  const [typeList, setTypeList] = useState<{ id: number; typeName: string }[]>(
    [],
  );
  // 获取需求类型
  const getRequirementsListType = async () => {
    const res = await HomeAPI.getRequirementsListType();
    if (res && res.code === '200') {
      setTypeList(res.result || []);
    }
  };
  // 获取当前服务的标签类型
  const getServiceTag = (i: ListType[0]) => {
    const item = serviceTagList.find((n) => n.code === i?.orderLevelEnum);
    return item || serviceTagList[0];
  };
  // 获取任务城市
  const getTaskCity = (i: ListType[0]) => {
    const item = formatLocationStr(i?.taskAddress);
    return item?.city || '深圳市';
  };
  // 获取任务时间
  const getTaskRange = (i: ListType[0]) =>
    `${dayjs(i?.taskStartTime).format('MM.DD')}~${dayjs(i?.taskEndTime).format(
      'MM.DD',
    )}`;
  // 获取任务类型
  const getTaskType = (i: ListType[0]) => {
    return typeList?.find((n) => n.id === i?.requirementTypeId)?.typeName;
  };
  // 获取保险列表
  const getInsuranceList = (i: ListType[0]) => {
    return (
      i?.insurance
        ?.split(',')
        ?.map((k) => insuranceList.find((n) => n.value === Number(k))?.name)
        ?.join(' | ') || '无'
    );
  };
  // 获取订单金额
  const getOrderAmount = (i: ListType[0]) => {
    const money = (bigNumberTransform(i?.orderAmount, true) as string)?.replace(
      '.00',
      '',
    );
    // formatMoney(props.detail?.orderAmount)
    return i?.orderAmount > 1 ? money : i?.orderAmount;
  };
  // 跳转详情
  const handleDetail = (item: ListType[0]) => {
    // 判断是否登录
    if (!userInfo?.id) {
      dispatch(
        setGlobalData({
          loginModalVisible: true,
        }),
      );
      return;
    }
    dispatch(
      setGlobalData({
        qrcodeModalVisible: true,
        qrcodeModalPath: 'page-order/order-flyer/index',
        qrcodeModalScene: `id=${Number(item?.id)}`,
      }),
    );
  };
  // 组件挂载
  useEffect(() => {
    getRequirementsListType().then();
    getAppPublishList().then();
  }, []);
  return (
    <HomeTaskWrap>
      <div className="task-title">
        <div className="title-label">抢单大厅</div>
        <QrcodePopover path={'page-service/service-task/index'}>
          <div className="title-more">
            <div className="more-label">更多</div>
            <div className="more-icon">
              <RightOutlined style={{ color: '#998e8b', fontSize: 13 }} />
            </div>
          </div>
        </QrcodePopover>
      </div>
      <div className="task-list">
        {requireList?.map((i, j) => (
          <div
            className="list-item list-none"
            key={j}
            onClick={() => handleDetail(i)}
          >
            <div className="item-title">
              {i?.orderLevelEnum !== 'REGULAR_ORDER' && (
                <div
                  className="title-tag"
                  style={{ background: getServiceTag(i)?.color }}
                >
                  {getServiceTag(i)?.icon || getServiceTag(i)?.text}
                </div>
              )}
              <div className="title-name">{i.requireDescription}</div>
            </div>
            <div className="item-tag flex-start">
              <div className="tag-item">{getTaskCity(i)}</div>
              <div className="tag-item">{getTaskRange(i)}</div>
              <div className="tag-item">{i?.serviceName}</div>
              <div className="tag-item">{getTaskType(i)}</div>
            </div>
            <div className="item-insurance flex-start">
              <SafetyCertificateFilled style={{ color: '#36C1AF' }} />
              <div className="text text-ellipsis">
                <span className="label">保险要求: </span>
                <span>{getInsuranceList(i)}</span>
              </div>
            </div>
            <div className="item-time">
              {dayjs(i?.createTime).format('MM-DD HH:mm')} 发布
            </div>
            {i?.orderAmount && (
              <div className="item-price">
                <span className="label">￥</span>
                <span className="num">{getOrderAmount(i)}</span>
              </div>
            )}
          </div>
        ))}
      </div>
    </HomeTaskWrap>
  );
};
export const HomeTaskWrap = styled.div`
  width: 100%;
  min-height: 8.71rem;
  background: linear-gradient(180deg, #ffe1d9 0%, #ffebe5 100%);
  box-sizing: border-box;
  padding: 1.13rem 1rem 1.17rem 1rem;
  .task-title {
    position: relative;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1rem;
    .title-label {
      font-size: 14px;
      font-weight: bold;
      color: #8b2c08;
      line-height: 1.04rem;
    }
    .title-more {
      display: flex;
      align-items: baseline;
      justify-content: flex-end;
      .more-label {
        font-size: 13px;
        font-weight: 400;
        color: #998e8b;
        margin-right: 0.2rem;
      }
    }
  }
  .task-list {
    position: relative;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .list-item {
      position: relative;
      width: calc((100% - 0.83rem * 3) / 4);
      min-height: 6rem;
      background: #ffffff;
      box-shadow: 0 0.25rem 0.5rem 0 rgba(204, 204, 204, 0.05);
      border-radius: 0.25rem;
      border: 0.02rem solid #ffffff;
      margin-right: 0.83rem;
      box-sizing: border-box;
      padding: 0.58rem 0.5rem 0.67rem 0.5rem;
      &:active,
      &:hover {
        filter: brightness(0.96);
      }
      &:last-child {
        margin-right: 0;
      }
      .item-title {
        position: relative;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-bottom: 0.5rem;
        .title-tag {
          position: relative;
          width: 18px;
          height: 18px;
          background: #ff0000;
          border-radius: 0.17rem;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 0.35rem;
          text-align: center;
          line-height: 18px;
          color: #ffffff;
          font-size: 13px;
        }
        .title-name {
          width: 60%;
          font-size: 14px;
          font-weight: bold;
          color: #333333;
          // 单行省略
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .item-tag {
        position: relative;
        width: 100%;
        margin-bottom: 0.5rem;
        .tag-item {
          position: relative;
          box-sizing: border-box;
          padding: 0.1rem 0.25rem;
          background: #fff5f4;
          border-radius: 0.08rem;
          font-size: 13px;
          font-weight: 400;
          color: #fe2910;
          margin-right: 0.33rem;
        }
      }
      .item-insurance {
        .text {
          margin-left: 0.2rem;
          font-size: 13px;
          font-weight: 400;
          color: #666666;
          width: 58%;
        }
      }
      .item-time {
        position: absolute;
        bottom: 0.67rem;
        right: 0.5rem;
        text-align: right;
        font-size: 12px;
        font-weight: 400;
        color: #999999;
      }
      .item-price {
        position: absolute;
        top: 0.5rem;
        right: 0.5rem;
        text-align: right;
        font-size: 16px;
        font-weight: 600;
        color: #fe2910;
      }
    }
  }
`;
export default HomeTaskView;
