import { CSSProperties, FC, PropsWithChildren, useState } from "react";
import "./index.less";
import {
  View,
  Form,
  Input,
  Text,
  Button,
  Picker,
  Image,
} from "@tarojs/components";
import Container from "@/components/Container";
import joinIcon from "@/assets/images/kitchenWaste/join.svg";
import Taro, { useDidShow } from "@tarojs/taro";
import globalStore from "@/store";
import api from "@/services";
import { useSetState } from "ahooks";
import dayjs from "dayjs";

interface FormItemProps {
  style?: CSSProperties;
  label: string;
}
export const FormItem: FC<PropsWithChildren<FormItemProps>> = ({
  children,
  style,
  label,
}) => {
  return (
    <View style={style}>
      <View className="form-item">
        <Text>{label}</Text>
      </View>
      {children}
    </View>
  );
};
/**
 * @description 收运记录
 */
const Record: FC = () => {
  const { businessId } = Taro.getCurrentInstance().router?.params || {};
  const [selectedIds, setSelectedIds] = useSetState<{
    k1?: any;
    k2?: any;
  }>({});
  const [selectedDate, setSelectedDate] = useSetState<{
    date: string;
    time: string;
  }>({
    date: "",
    time: dayjs().format("HH:mm"),
  });
  const [vehicles, setVehicles] = useState<API.CarListDot[]>([]);
  const [signEntities, setSignEntities] = useState<API.MerchantsListDot[]>([]);
  const { collectionInfo } = globalStore();

  useDidShow(() => {
    api.kitchenWaste.queryCarList().then((res) => {
      if (res.code === 200) {
        setVehicles(res.data);
      }
    });

    api.kitchenWaste.getSignEntities().then((res) => {
      if (res.code === 200) {
        setSignEntities(res.data);
        let index = res.data?.findIndex((v) => v.value === businessId);
        setSelectedIds({
          k1: index !== -1 ? index.toString() : undefined,
        });
      }
    });
  });

  //提交表单
  const formSubmit = (e) => {
    let { value } = e.target;
    for (let i in value) {
      if (!value[i]) {
        Taro.showToast({
          title: "请填写完整数据后再提交！",
          icon: "error",
          duration: 2000,
        });
        return;
      }
    }
    const { collectionDate, ...reset } = value;
    let params = {
      ...reset,
      carNum: vehicles[value.carNum].label,
      businessName: signEntities[value.businessName].name,
      businessId: signEntities[value.businessName].value,
      collectionId: collectionInfo?.id,
      collectionTime: value.collectionDate + ` ${value.collectionTime}:00`,
    };
    api.kitchenWaste.submitForWl(params).then((res) => {
      if (res.code === 200) {
        Taro.showToast({
          title: "提交成功",
          icon: "success",
          duration: 2000,
          mask: true,
          success: () => {
            setTimeout(() => {
              Taro.navigateBack();
            }, 800);
          },
        });
      } else {
        Taro.showToast({
          title: res.msg ?? "",
          icon: "error",
          duration: 2000,
        });
      }
    });
  };

  return (
    <Container title="电子五联单" style={{ backgroundColor: "#EEF7EF" }}>
      <View className="main">
        <Form onSubmit={formSubmit}>
          <FormItem label="产生单位">
            <Picker
              name="businessName"
              mode="selector"
              rangeKey="name"
              value={selectedIds.k1}
              range={signEntities}
              onChange={(e: any) => {
                setSelectedIds({ k1: e.detail.value });
              }}
            >
              <View className="form-input">
                {selectedIds.k1 !== undefined ? (
                  signEntities[selectedIds.k1].name
                ) : (
                  <Text className="placeholder">请选择单位</Text>
                )}
                <View className="select-text">
                  请选择 <Image src={joinIcon} />
                </View>
              </View>
            </Picker>
          </FormItem>
          <FormItem label="收运单位" style={{ marginTop: 29 }}>
            <Input
              name="collectionName"
              defaultValue={collectionInfo?.name ?? ""}
              className="form-input"
              placeholder="输入收运单位"
            />
          </FormItem>
          <FormItem label="收运重量" style={{ marginTop: 29 }}>
            <Input
              type="digit"
              name="weight"
              className="form-input"
              placeholder="输入收运重量"
            />
          </FormItem>
          <FormItem label="收运人" style={{ marginTop: 29 }}>
            <Input
              name="personnelName"
              className="form-input"
              placeholder="输入收运人"
            />
          </FormItem>
          <FormItem label="车辆" style={{ marginTop: 29 }}>
            <Picker
              name="carNum"
              mode="selector"
              rangeKey="label"
              range={vehicles}
              onChange={(e: any) => {
                setSelectedIds({ k2: e.detail.value });
              }}
            >
              <View className="form-input">
                {selectedIds.k2 ? (
                  vehicles[selectedIds.k2].label
                ) : (
                  <Text className="placeholder">请选择车辆</Text>
                )}
                <View className="select-text">
                  请选择 <Image src={joinIcon} />
                </View>
              </View>
            </Picker>
          </FormItem>
          <FormItem label="收运日期" style={{ marginTop: 29 }}>
            <Picker
              name="collectionDate"
              mode="date"
              value={selectedDate.date}
              onChange={(e) => {
                setSelectedDate({ date: e.detail.value });
              }}
            >
              <View className="form-input">
                {selectedDate.date || (
                  <Text className="placeholder">请选择收运日期</Text>
                )}
                <View className="select-text">
                  请选择 <Image src={joinIcon} />
                </View>
              </View>
            </Picker>
          </FormItem>
          <FormItem label="收运时间" style={{ marginTop: 29 }}>
            <Picker
              name="collectionTime"
              mode="time"
              value={selectedDate.time}
              onChange={(e) => {
                setSelectedDate({ time: e.detail.value });
              }}
            >
              <View className="form-input">
                {selectedDate.time || (
                  <Text className="placeholder">请选择收运时间</Text>
                )}
                <View className="select-text">
                  请选择 <Image src={joinIcon} />
                </View>
              </View>
            </Picker>
          </FormItem>

          <Button formType="submit" className="sub-btn" plain>
            <Text>提交</Text>
          </Button>
        </Form>
      </View>
    </Container>
  );
};
export default Record;
